DEV Community

Anirban
Anirban

Posted on • Edited on

JavaScript Promise

A promise in JavaScript is an object that may produce a single value any time in the future. It may give us either a resolved value or a reason that it is not resolved (rejected). A promise can be in one of the following three states.

  • Fulfilled
  • Rejected
  • Pending

We can create a promise like below. The constructor function of the promise takes a function that has parameters that either resolves or rejects.

const promise = new Promise((resolve, reject) => {
    if (true) {
        resolve("It worked");
    } else {
        reject("Error, it broke");
    }
});
Enter fullscreen mode Exit fullscreen mode

Here, we can check the returned value from the promise by chaining with .then like below.

promise.then((result) => console.log(result));
Enter fullscreen mode Exit fullscreen mode

This should log "It worked" in the console as the promise was resolved.

We can catch the rejected value comes out of the promise by chaining with .catch like below.

const promise = new Promise((resolve, reject) => {
    if (false) {
        resolve("It worked");
    } else {
        reject("Error, it broke");
    }
});

promise
.then((result) => console.log(result))
.catch((err) => console.log(err));
Enter fullscreen mode Exit fullscreen mode

This code should write "Error, it broke" in the console.

Also, we can get the resolved results from the multiple promises using Promise.all() method.

const promise1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 100, "Promise1");
});

const promise2 = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, "Promise2");
});

const promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 5000, "Promise3");
});

Promise.all([promise1, promise2, promise3]).then((results) => {
    console.log(results);
});
Enter fullscreen mode Exit fullscreen mode

Here, we will get an array as an output in the console after 5 seconds. The output will look like [ 'Promise1', 'Promise2', 'Promise3' ].

That's all for today. If you like this post and want to talk more about it, please feel free to DM me here
Have a great one!

Top comments (0)