Promises in JavaScript

Promises in JavaScript

Table of contents

No heading

No headings in the article.

Hey there! Today in this blog we will discuss what is promise in javaScript, different states of promises, methods of promises, and how to create your own promises and resources that I used. So Let’s get into it!!

What is a Promise?

In Simple terms, promises are the same as we use the word promise in daily life. For example You do promise to buy the book today from the shop. So It indicates that you will do something in the future. Same in JavaScript promise is a proxy for a value that will eventually become available. It represents the completion of an asynchronous operation and its resulting value. So that asynchronous operation return promise which will have value available in future.

A promise has 3 states,

  1. Pending
  2. Fulfilled
  3. Rejected

How Promise actually works?

When the first promise is called, it is in a pending state. For example when we fetch data from API and that returns a promise. So while before getting data it is in a pending state. It will be in pending until it gets resolved. Once the promise is resolved then it will be in the Fulfilled state and if it gets rejected then the promise will be in the rejected state. So pending is an initial state, Fulfilled is the sign of successful completion of the operation, and Rejected shows that the operation has failed.

How to create your own Promise?

In JavaScript, a promise can create using a promise constructor. It will take two callbacks, the first is resolve and the second is reject. If the operation is completed successfully then resolve will be used in the promise and it returns the result value. At that time promise will be in a fulfilled state. If the operation failed then the promise gets rejected and it calls the reject function. Which will return an error if occurred. Now promise will be in the rejected state.

image.png

Source: MDN docs

let isTrue = true;
const myPromise = new Promise((resolve, reject) => {
  if (isTrue) {
    resolve("yay! operation completed sucessfully");
  } else {
    reject("oh no, operation failed!");
  }
});

Here I have created myPromise using the Promise constructor. Where I have given two arguments, resolve and reject which are callbacks. If a condition is true then it will call resolve otherwise use reject. Likewise, you can create your own promise.

To get the result value from the promise you can .then. Let’s learn how to do that.

myPromise.then(
  (result) => console.log(result),
  (error) => console.log(error)
);

Here we have used .then which the first argument is the function that runs when the promise gets resolved and it gets the result value. The second argument is the function that runs when the promise gets rejected and gets the error. We can also use catch here to get the error.

let isTrue = false;
const myPromise = new Promise((resolve, reject) => {
  if (isTrue) {
    resolve("yay! operation completed sucessfully");
  } else {
    reject("oh no, operation failed!");
  }
});

myPromise.catch((error) => console.log(error));

Yay! you know how to create the promise.

cute.gif

✏️ Create your own promise and share it in the comments below.

Methods of Promise

  1. Promise.all()

    It is used to get the list of promises that is resolved. It will return in the same order as defined. It takes promises as an input and returns a single Promise that resolves to an array of the results of the input promises. If any promise gets rejected then it shows the error message.

     const firstPromise = myPromise;
     const secondPromise = Promise.resolve("resolved!");
    
     Promise.all([firstPromise, secondPromise])
       .then((res) => {
         console.log(res);
       })
       .catch((err) => {
         console.error(err);
       });
     // ["yay! operation completed sucessfully", "resolved!"]
    
  2. Promise.race

    It takes promises as inputs and runs the function once that returns when any of the promise get resolved or rejected.

     const firstPromise = new Promise((resolve, reject) => {
       setTimeout(resolve, 500, 'first')
     })
     const secondPromise = new Promise((resolve, reject) => {
       setTimeout(resolve, 100, 'second')
     })
    
     Promise.race([firstPromise, secondPromise]).then(result => {
       console.log(result) // second
     })
    
  3. Promise.any()

    It takes promises as input and returns a single promise that any of the promises get resolved. If no promise is fulfilled then it returns a promise rejected with an error.

     const firstPromise = Promise.reject(0);
     const secondPromise = Promise.reject(1);
     const thirdPromise = Promise.reject(2);
    
     const promises = [firstPromise, secondPromise, thirdPromise];
    
     Promise.any(promises).then((value) => console.log(value));
     //AggregateError All promises were rejected
    
     const firstPromise = Promise.reject(0);
     const secondPromise = new Promise((resolve) => setTimeout(resolve, 100, "quick"));
     const thirdPromise = new Promise((reject) => setTimeout(reject, 500, "slow"));
    
     const promises = [firstPromise, secondPromise, thirdPromise];
    
     Promise.any(promises).then((value) => console.log(value));
     //  "quick"
    

    I have used the below resources to learn promises and to write this blog.

    Resources:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    https://javascript.info/promise-basics

    https://nodejs.dev/learn/understanding-javascript-promises

    In the end, I recommend you don't just read and look at the code! Do experiments with it! Thank you. See you in the next one 👋