Promises in Javascript

CodeyMaze
2 min readMar 7, 2022

--

Promises in JavaScript are used to deal with asynchronous operations. JavaScript is an asynchronous single-threaded language. We can make use of callbacks or promises to handle asynchronous operations. Promises provide a better alternative to callbacks.

A Promise is the same as a promise in real life. If we made a promise to someone then either that promise will get fulfilled or rejected. Same in JavaScript as well, a promise can be in one of two states — Fulfilled or Rejected.

How to create promise

To create a promise, we can make use of the promise construction function.

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

The Promise constructor function takes a callback function and this callback function will accept two parameters — resolve & reject. Resolve will be used if the promise gets fulfilled and reject will be used if the promise is unfulfilled. There are two methods to handle the resolve and reject.

Then() method will be called if the promise gets resolved and catch() will be called if the promise gets rejected.

Below is an example of Promise to check if the value of the result is true or not. If true, we will resolve, otherwise, reject.

Promise Chaining

Let us say we need to call more than one API one after another, in this scenario, if we use callback then it will be like multiple nested callbacks placed inside each other. This scenario is known as callback hell. Promises provide us with a more structured way of doing these things with the help of promise chaining.

We can do promise chaining by appending multiple .then() handlers to one another. We can add as many numbers of .then() handlers we want.

Here is an example of simple promise chaining:

In the above code, calling resolve with the value of 1 will go to first then handler, ‘First, then block executed 1’ will get printed to the console, and value of result * 2 will be returned. This will go to next then handler, ‘Second then block executed 2’ will get printed to the console and so on.

If we call reject from the promise, it will go directly to catch block.

Subscribe to our Youtube channel for more videos :

https://www.youtube.com/channel/UCEXWe9R6-ppk4zhNo2JbtmQ

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet