Promise in JavaScript and methods

What is promise and why we use it?

We will take a real life example, your best friend calls you and tell you that he is getting married soon, and he asks you to come.

And being a good friend, you promised him that 'Sure! I will come'. Now if you go to the marriage, the promise is fulfilled by you, but if you had some emergency or any important work, then the promise will be rejected.

So this is same in JavaScript. Either a promise get fulfilled or rejected. Why we use Promise? As JavaScript is a synchronous language, it executes one line at a time. Now, the problem arises when we want to do certain operations only when a data becomes available, and if it is taking time, then other lines of the code will not be executed, and this is not what we want. We don't want our application or website to stop other work until we get the data(for example : data from an API). So that's why we use Promise, because now other lines of the code will execute without any problem.

Promise syntax:

let promise = new Promise(function(resolve, reject) {    
  setTimeout(() => {
    resolve('promise is resolved');// we are resolving promise here
  },3000);
});
promise.then(data => console.log(data));// promise is resolved
let promise = new Promise(function(resolve, reject) {    
  setTimeout(() => {
    reject('promise is rejected');//we are rejecting promise here 
  },3000);
});

promise.catch(data => console.log(data));// promise is rejected

Now let's abstract the above code, and do resolved/ rejected operation in single code

let promise = new Promise(function(resolve, reject) {    
  setTimeout(() => {
    resolve('promise is resolved'); // You can also write reject in place of resolve and see the result
  },3000);
});

promise.then(data => console.log(data)).catch(err => console.log(err))

Now what the hell is .then().catch()? This is what we call promise chaining, so basically when promise is rejected/resolved, we are telling what need to be done.

For example in the above code snippet we are telling, when promise is resolved then, then block will run, and some operation will be performed(In the above example, promise is resolved will be shown in the console), and if promise is rejected then, catch block is executed.

Now let's take another example

Promise resolved

let promise = new Promise(function(resolve, reject) {    
  let dog = 'bark';
  setTimeout(() => {
    dog === 'bark' ? resolve("dog barks") : resolve("dog doesn't meow");
  },3000);
});

promise.then(data => console.log(data)).catch(err => console.log(err))// promise resolve with the value 'dog barks'

Promise rejected

let promise = new Promise(function(resolve, reject) {    
  let dog = 'meow';
  setTimeout(() => {
    dog === 'bark' ? resolve("dog barks") : resolve("dog doesn't meow");
  },3000);
});

promise.then(data => console.log(data)).catch(err => console.log(err))// promise rejects with the value 'dog doesn't meow'

In the above code we can see if dog variable value set to bark then the promise get resolved, otherwise it get rejected.

Some promise methods

Promise.all()

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. When we have many promises, instead of writing promise.then() for each, what we can do we can use Promise.all() method, it takes promises in the form of array. Let's see with the help of an example

let promise1 = new Promise(function(resolve, reject) {    
  let dog = 'bark';
  setTimeout(() => {
    dog === 'bark' ? resolve("dog barks") : resolve("dog doesn't meow");
  },3000);
});

let promise2 = new Promise(function(resolve, reject) {    
  let dog = 'meow';
  setTimeout(() => {
    dog === 'bark' ? resolve("dog barks") : resolve("dog doesn't meow");
  },3000);
});

Promise.all([promise1, promise2]).then((values) => {
  console.log(values); // ['dog barks', 'dog doesn't meow']
});

Whether the promise is rejected or resolved, it gives us the end result that too in the form of an array.

Promise.any()

Lets understand with the help of an example

let promise1 = new Promise(function(resolve, reject) {    
  setTimeout(() => {
    resolve('promise is resolved');// we are resolving promise here
  },1000);
});
let promise2 = new Promise(function(resolve, reject) {    
  setTimeout(() => {
    reject('promise is rejected')we are rejecting promise here
  },1000);
});

Promise.any([promise1, promise2]).then((values) => {
  console.log(values); // promise is resolved
});

When we use promise.any() method, the very first promise which get resolved will be returned, it will not check the other promise. In the above code as soon as promise resolved is encountered then promise2 will not run. But if all the values are rejected, they it will throw an error. Run the below code to observe this.

let promise1 = new Promise(function(resolve, reject) {    
  setTimeout(() => {
    reject('promise is resolved');// we are resolving promise here
  },1000);
});
let promise2 = new Promise(function(resolve, reject) {    
  setTimeout(() => {
    reject('promise is rejected')
  },1000);
});

Promise.any([promise1, promise2]).then((values) => {
  console.log(values); // ['dog barks', 'dog doesn't meow']
}).catch(err => console.log(err));