Promises

A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.

Simply, a promise is a container for a future value. If you think for a moment, this is exactly how you use the word promise in your normal day-to-day conversation. For example, you book a flight ticket to go to India for travelling to the beautiful hill station Darjeeling. After booking, you get a ticket. That ticket is a promise by the airline that you will get a seat on the day of your departure. In essence, the ticket is a placeholder for a future value, namely, the seat.

We create a promise when a certain task’s completion time is uncertain or too long. For example — A network request may take anywhere between 10ms to 2000ms (or more) depending on the connection’s speed. We don’t want to wait while the data is being fetched. Promises are all about making this type of asynchrony easy and effortless.

A new promise is created by the using the Promise constructor. Like this:

const myPromise = new Promise((resolve, reject) => {
    if (Math.random() * 100 <= 90) {
        resolve('Hello, Promises!');
    }
    reject(new Error('In 10% of the cases, I fail. Miserably.'));
});

Observe that the constructor accepts a function with two parameters. This function is called an executor function and it describes the computation to be done. The parameters conventionally named resolve and reject, mark successful and unsuccessful eventual completion of the executor function, respectively.

The resolve and reject are functions themselves and are used to send back values to the promise object. When the computation is successful or the future value is ready, we send the value back using the resolve function. We say that the promise has been resolved.

If the computation fails or encounters an error, we signal that by passing the error object in the reject function. We say that the promise has been rejected. reject accepts any value. However, it is recommended to pass an Error object since it helps in debugging by viewing the stacktrace.

How can we access the the value passed by the resolve or reject function?

All Promise instances have a .then() method. .then() accepts two callbacks. The first callback is invoked when the promise is resolved. The second callback is executed when the promise is rejected.

myPromise.then((resolvedValue) => {
    console.log(resolvedValue);
}, (error) => {
    console.log(error);
});

Last updated