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.

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.


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.
const promises = [1, 2, 3].map((item) => Promise.resolve(item));
Promise.all(promises).then(console.log); // [1, 2, 3]
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);
    }
  });
};

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.

const promises = [Promise.resolve(1), Promise.reject(2), Promise.resolve(3)];
Promise.race(promises).then(console.log); // 1
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

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.

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}]
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}]

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.

const promises = [Promise.reject(1), Promise.reject(2), Promise.resolve(3)];
Promise.any(promises).then(console.log); // 3
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

It returns a resolved promise.

Promise.resolve(1).then(console.log); // 1
const resolve = (value) => {
  return new Promise((resolve) => resolve(value));
};

resolve(1).then(console.log); // 1

It returns a rejected promise.

Promise.reject(1).catch((err) => console.log(err)); // 1
const reject = (value) => new Promise((resolve, reject) => reject(value));

reject(1).catch((err) => console.log(err)); // 1

Thank you for reading 😊

Got any questions or additional? please leave a comment.


More content at Blogspot

Catch me on GithubTwitterLinkedInMediumDev.tohashnode Stackblitz.

Next Post Previous Post
No Comment
Add Comment
comment url