DEV Community

Cover image for Javascript Promise Methods with polyfill example: A Cheat Sheet for Developer
Rahul Sharma
Rahul Sharma

Posted on • Edited on

Javascript Promise Methods with polyfill example: A Cheat Sheet for Developer

Promise helps to do something asynchronously, It is a way to handle asynchronous operations in JavaScript.

All You Need to Know About JavaScript Promises methods and Polyfill

Promise consists of three states:

  1. Pending: Initial State, neither fulfilled nor rejected.
  2. Fulfilled: Completed Promise (success)
  3. Rejected: Failed Promise (failure)

Without wasting time, Let's learn about the Promise functions.

Note: I've also added a Polyfill example, Which will help you to understand easily and also help you if you are preparing for the interview.

1. Promise.all

Promise.all takes an array of promises as input and returns a promise object. The returned promise will be resolved when all the promises in the input array are resolved. If any of the promises in the input array is rejected, the returned promise will be rejected with the reason for the first rejected promise.

Example:
const promises = [1, 2, 3].map((item) => Promise.resolve(item));
Promise.all(promises).then(console.log); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
Polyfill Example:
const all = (promises) => {
  return new Promise((resolve, reject) => {
    const result = [];
    let count = 0;
    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then((res) => {
        result[i] = res;
        count++;
        if (count === promises.length) {
          resolve(result);
        }
      }, reject);
    }
  });
};
Enter fullscreen mode Exit fullscreen mode

2. Promise.race

It takes an array of promises as input and returns a promise object. The returned promise will be resolved/rejected as soon as one of the promises in the input array is resolved/rejected.

Example:
const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
Promise.race(promises).then(console.log); // 1
Enter fullscreen mode Exit fullscreen mode
Polyfill Example:
const race = (promises) => {
  return new Promise((resolve, reject) => {
    promises.forEach((promise) =>
      Promise.resolve(promise).then(resolve, reject)
    );
  });
};

const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
race(promises).then(console.log); // 1
Enter fullscreen mode Exit fullscreen mode

3. Promise.allSettled

It takes an array of promises as input and returns a promise object. The returned promise will be resolved when all the promises in the input array are settled. The returned promise will be resolved with an array of objects that each describes the outcome of each promise in the input array.

Example:
const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
Promise.allSettled(promises).then(console.log); // [{status: "fulfilled", value: 1}, {status: "rejected", reason: 2}, {status: "fulfilled", value: 3}]
Enter fullscreen mode Exit fullscreen mode
Polyfill Example:
const allSettled = (promises) => {
  return new Promise((resolve) => {
    const result = [];
    let count = 0;

    const handleResult = (value, index, status) => {
      result[index] = { status, value };
      count++;
      if (count === promises.length) {
        resolve(result);
      }
    };

    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then(
        (res) => handleResult(res, i, "fulfilled"),
        (err) => handleResult(err, i, "rejected")
      );
    }
  });
};

const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
allSettled(promises).then(console.log); // [{status: "fulfilled", value: 1}, {status: "rejected", reason: 2}, {status: "fulfilled", value: 3}]
Enter fullscreen mode Exit fullscreen mode

4. Promise.any

It takes an array of promises as input and returns a promise object. The returned promise will be resolved when any of the promises in the input array is resolved. If all of the promises in the input array are rejected, the returned promise will be rejected with an error array.

Example:
const promises = [Promise.reject(1), Promise.reject(2), Promise.resolve(3)];
Promise.any(promises).then(console.log); // 3
Enter fullscreen mode Exit fullscreen mode
Polyfill Example:
const any = (promises) => {
  return new Promise((resolve, reject) => {
    const result = [];
    let count = 0;

    const handleResult = (value, index, status) => {
      result[index] = { status, value };
      count++;
      if (count === promises.length) reject(result);
    };

    for (let i = 0; i < promises.length; i++) {
      promises[i].then(resolve, (err) => handleResult(err, i, "rejected"));
    }
  });
};

const promises = [Promise.reject(1), Promise.reject(2), Promise.resolve(3)];
any(promises).then(console.log); // 3
Enter fullscreen mode Exit fullscreen mode

5. Promise.resolve

It returns a resolved promise.

Example:
Promise.resolve(1).then(console.log); // 1
Enter fullscreen mode Exit fullscreen mode
Polyfill Example:
const resolve = (value) => {
  return new Promise((resolve) => resolve(value));
};

resolve(1).then(console.log); // 1
Enter fullscreen mode Exit fullscreen mode

6. Promise.reject

It returns a rejected promise.

Example:
Promise.reject(1).catch((err) => console.log(err)); // 1
Enter fullscreen mode Exit fullscreen mode
Polyfill Example:
const reject = (value) => new Promise((resolve, reject) => reject(value));

reject(1).catch((err) => console.log(err)); // 1
Enter fullscreen mode Exit fullscreen mode

Thank you for reading 😊

Got any questions or additional? please leave a comment.


Must Read If you haven't
3 steps to create custom state management library with React and Context API
How to cancel Javascript API request with AbortController
Getting started with SolidJs – A Beginner's Guide

More content at Dev.to.
Catch me on Youtube, Github, Twitter, LinkedIn, Medium, Stackblitz, Hashnode, HackerNoon, and Blogspot.

Top comments (0)