In this article, we will see Promises.

start

Promises in javascript are the same as promises in real-life ie result-oriented conditions.

According to MDN :

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.

In simpler words, it means a Promise is an object which returns a value in future. The result could be anticipated one i.e positive or if anything goes wrong it could be something not anticipated i.e negative.

It’ll be easier to understand the concept of JavaScript promises through an analogy.

Suppose that you promise to complete making your portfolio website by next week.

You don’t know if you will spend your time and effort to make your portfolio website until next week. You can either be complete making your portfolio website or not.

Promises in javascript have one of these states:

  1. Pending: you don’t know if you will complete making your portfolio by the next week.

2. Fulfilled: you complete making your portfolio website by the next week.

  1. Rejected: you don’t make your portfolio website at all.

Creating a promise

To create a promise we use the Promise constructor.

let completed = true;

let completePortfolio = new Promise(function (resolve, reject) {
    if (completed) {
        resolve("I have completed making my portfolio website.");
    } else {
        reject("I haven't completed making my portfolio website yet.");
    }
});

The Promise constructor accepts a function as an argument. This function is called the executor.

The executor accepts two functions with the names, by convention, resolve() and reject().

Screenshot from 2021-07-13 11-20-36.png

Promise consumers(then,catch,finally)

then()

Syntax:

promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

The first argument of then is a function that runs when the promise is resolved and receives a result. The second argument is run when the promise is rejected and receives an error.

completePortfolio.then(
  result => console.log(result), // shows "I have completed making my portfolio website."
  error => console.log(error) // doesn't run
);

catch

If we are interested only in errors then we use catch()

completePortfolio.catch(
    reason => console.log(reason)
);

finally

finally is used when we want to use the same piece of code when a promise is resolved or rejected.

function createApp() {
    // ...
}
completePortfolio.then(
        (success) => {
            console.log(success);
            createApp();
        }
    ).catch(
        (reason) => {
            console.log(reason);
            createApp();
        }
    );

The above code is the same as:

 completePortfolio .then(success => console.log(success))
  .catch(reason => console.log(reason))
 .finally(() => createApp());

Promise Chaining

According to MDN docs:

A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. We accomplish this by creating a promise chain.

Let us understand it with a help of example.

Example:

let x = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(10);
    }, 3 * 100);
});

x.then((result) => {
    console.log(result);//10
    return result * 2;
}).then((result) => {
    console.log(result);//20
    return result * 3;
});

//output:
10
20

The following pic illustrates the above code:

Screenshot from 2021-07-13 12-23-45.png

Note: ES2017 introduced the async/await keywords that help you write cleaner code than using this promise chain technique.

Promise.all()

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that :

  • resolves when every input Promise has resolved or

  • rejected when any of the input Promise has rejected.

The Promise.all() is useful when you want to aggregate the results from multiple asynchronous operations.

const p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('The first promise has resolved');

        resolve(10);
    }, 1 * 1000);

});
const p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('The second promise has resolved');
        resolve(20);
    }, 2 * 1000);
});

Promise.all([p1, p2])
    .then(results => {
        const total = results.reduce((p, c) => p + c);


        console.log(`Total: ${total}`);//30
    });

That's it for this article thanks for reading. If you like my articles, subscribe to the newsletter or connect with me on Twitter.

thanks

Â