DEV Community

Cover image for How to use Promise in JavaScript
Taimoor Sattar
Taimoor Sattar

Posted on • Originally published at taimoorsattar.dev

How to use Promise in JavaScript

Promise in JavaScript is the way to wait for a certain action to process or complete. The promise has the following states:

  • Pending: incomplete (initial state), neither fulfilled nor rejected.
  • Fulfilled: The process was successfully completed.
  • Rejected: The process failed.

So, where the promise is useful? We can use promise in JavaScript in a different situation. For example:

We can use fetch in JavaScript to retrieve the data from a certain API endpoint. The fetch in JavaScript is a promise that returns the data if the request is successfully processed.

Let's take an example. We have 1st person that's giving the promise and 2nd person that's waiting for the promise to fulfill.

In JavaScript, we can define the promise as below:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    if(Math.random() > 0.5){
      resolve('foo');
    }else{
      reject("Exception!")
    }
  }, 300);
});
Enter fullscreen mode Exit fullscreen mode

In the above, we define the promise that waits for 0.3 seconds and returns the pass or fails message based on the boolean logic (true or false).

Now, to wait for the promise to complete, we can write code in JavaScript as below:

myPromise
.then(value => { return value + ' and bar'; })
.then(value => { console.log(value) })
.catch(err => { console.log(err) })
.finally(() => {
    console.log('Promise completed');
});
Enter fullscreen mode Exit fullscreen mode

In the above code, the following callback function runs:

.then: Executes when the process is successfully completed
.catch: Executes when the process is failed
.finally: execute at every condition


Moving further... Let's say, we have more than one person that is giving the promise. We can define in JavaScript as below:

const promise1 = Promise.resolve("great");
const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 300, 'Yesss!!!');
});
Enter fullscreen mode Exit fullscreen mode

We can use Promise.all that returns a promise which resolves after all of the given promises have either fulfilled or rejected. We can write in JavaScript as below:

Promise.all([promise1, promise2]).then((values) => {
  console.log(values);
})
.catch(error => {
  console.error(error.message)
});
Enter fullscreen mode Exit fullscreen mode

The above code will log the following in the console:

["great","Yesss!!!"]
Enter fullscreen mode Exit fullscreen mode

The previous example works OK if all the promises resolve successfully. But... let's say, If one of the promises is rejected, the overall Promise.all will be rejected even if every other promise is resolved successfully.

Let say, If we are waiting for many promises. Some promises got fulfilled and some are rejected. In JavaScript, we can define promise as below:

var p1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('p1_delayed_resolution1'), 1000);
});

var p2 = new Promise((resolve, reject) => {
  reject(new Error('p2_immediate_rejection'));
});
Enter fullscreen mode Exit fullscreen mode

In Promise.all, we can use the .catch statement to handle the error of each promise.

Promise.all([
  p1.catch(error => { return error }),
  p2.catch(error => { return error }),
]).then(values => {
  console.log(values[0]) // "p1_delayed_resolution"
  console.error(values[1]) // "Error: p2_immediate_rejection"
})
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
rish15 profile image
rish srivastav

Might wanna add async/await as well at-least a snippet of it

Collapse
 
ellisotoo profile image
Ellis Otoo

Makes so much sense now

Collapse
 
nwaforaugustine321 profile image
Nwafor Augustine

Good article

Collapse
 
taimoorsattar7 profile image
Taimoor Sattar

Thanks