📄 Table of Contents

▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Brief Introduction to Promises

Promises in JavaScript are very similar to the promises you make in your daily life, a kind of assurance that something will be done in the future.

According to MDN Docs, A Promise is an object representing the eventual completion or failure of an “Asynchronous” operation.

Promises allow you to attach callback handlers to handle the future asynchronous success value or failure reason.

Before diving deep into promises let’s understand what exactly is a callback.

◉ What is a Callback?

A callback is a function that is passed into another function as an argument to be executed later.

They’re so common in JavaScript that you probably used callbacks yourself without knowing they’re called callbacks. Here, is an example of setTimeout() function callback:

In the example above, setTimeout() waits for three seconds and is called after something happened (after 3 seconds passed for this example), but not before.

Callback Hell

Now let’s imagine a scenario where you want to wait another 3 seconds after the first callback has finished, and do something. Your code will look like the following:

And now if you want to do something after the second callback has finished, you will get another nested callback:

Nested callbacks make it difficult to maintain and scale the code. In the code above, we have three levels of nested functions, one for each setTimeout() call. Having an application with tens of nested callbacks will make the developers live hell to update or even understand the code. Such a situation is referred to as callback hell.

That’s where the JavaScript promises come into the picture.

◉ JavaScript Promises

Promises are NOT meant to replace the callbacks. Instead, they simplify the chaining of functions, making it easier to read and maintain the code. A promise can be in one of the following states:

Different states of a promise:-

A pending promise can either be resolved (fulfilled) with a value or rejected with a reason. Once settled, a promise can not be resettled.

◉ Creating a Promise

To create a promise in JavaScript, you use the Promise constructor:

const myPromise = new Promise();

It takes two parameters, one for success (resolve) and one for fail (reject):

const myPromise = new Promise((resolve, reject) => {  
// condition
});

Inside the Promise, you manually call the resolve() function if the promise is completed successfully and invoke the reject() function in case an error occurs.

let completed = true;
const myPromise = new Promise((resolve, reject) => {
if(completed) {
resolve('Promise is resolved successfully.');
} else {
reject('Promise is rejected');
}
});

After executing the above promise in the browser console you will see that the promise is resolved because the completed variable is set to true

To see the pending state of the promise, we wrap the code of the Promise in the setTimeout() function:

let completed = true;
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if(completed) {
resolve('Promise is resolved successfully.');
} else {
reject('Promise is rejected');
}
}, 3000)
});

Now, you see that the promise starts with the pending state with the value is undefined. The promise value will be returned later once the promise is completed.

After about 3 seconds, type myPromise in the console window, you will see that the state of the promise becomes resolved and the promise value is the string that we passed to the resolve() function.

If you change the value of the completed variable to false and run the promise again you will see an error message and the state of the promise becomes rejected after 3 seconds:

Consuming a Promise: then, catch, finally

1) The .then() method

The then() method is used to schedule a callback to be executed when the promise is successfully resolved.

For example, let’s log the message to the console that we got from the Promise:

2) The catch() method

If you want to schedule a callback to be executed when the promise is rejected, you can use the catch() method of the Promise object:

So if the promise gets rejected, it will jump to the catch() method and this time we will see a different message on the console.

3) The finally() method

Sometimes, you want to execute any piece of code whether the promise is fulfilled or rejected.

The finally() method is called once the promise is settled irrespective of whether it is resolved or rejected.

◉ promise.race, any, all, allSettled

The native Promise object has some extra stuff you might be interested in:

Promise.any

The Promise.any method takes an array of Promises and will return as soon as the first one is Fulfilled.

Promise.race()

Promise.race() method accepts a list of promises and returns a promise that fulfills or rejects as soon as there is one promise that fulfills or rejects, with the value or reason from that promise.

This is very similar to the Promise.any method, however, it has one key difference. While Promise.any will return only if one of the promises is Fulfilled, Promise.race will return if any of the promises are Settled.

Promise.all()

Promise.all() method is useful to execute multiple promises in parallel and waits until all of them are ready. It takes an array of promises as an input and returns a single promise, that resolves when all of the promises get resolved or any one of them gets rejected.

Promise.allSettled()

Promise.allSettled() method wait’s until all promises have settled (each may resolve or reject). Returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise.

Summary

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store