Codementor Events

Mastering JavaScript Promises: A Comprehensive Guide for Optimized Asynchronous Code

Published Jan 11, 2023Last updated Jan 16, 2023
Mastering JavaScript Promises: A Comprehensive Guide for Optimized Asynchronous Code

JavaScript is a powerful programming language that is widely used to build web applications and other software. One of the most important concepts in JavaScript is the idea of a promise and mastering it can help you to write more efficient and organized asynchronous code. In this post, we will explain what promises are, how they work, and why they are so important for writing efficient and organized code.

A promise is an object that represents the eventual completion of an asynchronous operation. It is a placeholder for a value that will be returned at some point in the future. This value can be a success or an error, depending on the outcome of the operation.

A promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Once a promise is fulfilled, it cannot be rejected or pending again, it will have its final state and value.
Promises can be in one of three states:

  • Pending: The initial state, neither fulfilled nor rejected.
  • Fulfilled: Meaning that the operation completed successfully.
  • Rejected: Meaning that the operation failed.

A promise is an object that represents a value that may not yet be available. The promise object has a then() method, which you can use to attach callbacks that will be invoked when the promise is resolved (meaning the value is available). The promise also has a catch() method, which you can use to attach callbacks that will be invoked if an error occurs while trying to resolve the promise.

Here's an example of a simple promise that represents a value that will be available after a 2 second delay:

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Hello World!');
    }, 2000);
});

myPromise
    .then(value => {
        console.log(value);  // "Hello World!"
    })
    .catch(error => {
        console.log(error);
    });

In this example, we create a new promise by passing a function to the Promise constructor. This function takes two arguments: resolve and reject. The function is called with these two arguments as soon as the promise is created. We use the setTimeout() function to simulate an asynchronous operation that takes 2 seconds to complete. Inside the setTimeout() callback, we call the resolve() function, which causes the promise to be resolved with the value "Hello World!".

We then attach a then() callback to the promise, which logs the value of the promise to the console when it is resolved. We also attach a catch() callback, which will log any errors that may occur while trying to resolve the promise.

Promise also have a .finally() method, that is used for perform some action after the promise is settled( whether fulfilled or rejected)

promise.finally(() => console.log('promise settled'));

Promise are also chainable, which means that we can chain multiple promise and keep track of each result in sequential order

let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 1000);
});

promise
    .then(result => result * 2)
    .then(result => result * 3)
    .then(result => {
      console.log(result);
    });

Promise.all and promise.race are other variants that can be used to handle multiple promise.
Promise.all is used when we want to do something after all the promises are fulfilled and promise.race is used when we want to do something as soon as one promise is fulfilled

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise 1');
  }, 200);
});
const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise 2');
  }, 100);
});

Promise.all([promise1, promise2])
  .then(values => {
    console.log(values);
  })
  .catch(error => {
    console.log(error);
  });

In this example, both the promises resolve with different values at different time, but with Promise.all we can wait for both promises to resolve and get an array of resolved values.

Promises in JavaScript are very powerful and can be used to handle a wide variety of use cases. They are particularly useful for handling the response from an API call or working with data that is loaded asynchronously.

Discover and read more posts from Saurabh Yadav
get started