Skip to content

Latest commit

 

History

History
138 lines (102 loc) · 4.2 KB

33.implement-Promise.allSettled.md

File metadata and controls

138 lines (102 loc) · 4.2 KB

33. implement Promise.allSettled()

Promise.allSettled is a method in JavaScript that takes an iterable (such as an array) of promises and returns a single promise. This returned promise resolves when all the promises in the iterable have settled, meaning each promise has either resolved or rejected. It does not reject if any of the promises reject; instead, it provides the outcome of each promise.

Key Features of Promise.allSettled

  1. Settling of All Promises:

    • Promise.allSettled waits for all promises in the iterable to settle (either resolved or rejected).
    • It returns a promise that resolves with an array of objects describing the outcome of each promise.
  2. Resolved Value:

    • The array contains objects with two properties: status and either value (if resolved) or reason (if rejected).

    • Example:

      [
        { status: "fulfilled", value: result1 },
        { status: "rejected", reason: error }
      ]
  3. No Immediate Rejection:

    • Unlike Promise.all, it does not reject immediately if any promise rejects. Instead, it waits for all promises to settle and provides their outcomes.

Problem

https://bigfrontend.dev/problem/implement-Promise-allSettled

Problem Description

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

from MDN

Different from Promise.all() which rejects right away once an error occurs, Promise.allSettled() waits for all promises to settle.

Now can you implement your own allSettled()?

Solution

/**
 * @param {Array<any>} promises - notice that input might contains non-promises
 * @return {Promise<Array<{status: 'fulfilled', value: any} | {status: 'rejected', reason: any}>>}
 */
function allSettled(promises) {
  if (promises.length === 0) {
    return Promise.resolve([]);
  }

  const results = Array(promises.length);
  let numOfSettledPromise = 0;

  return new Promise((resolve, reject) => {
    promises.forEach((promise, i) => {
      if (!(promise instanceof Promise)) {
        promise = Promise.resolve(promise);
      }

      promise.then(
        (value) => {
          results[i] = {
            status: 'fulfilled',
            value,
          };

          numOfSettledPromise++;
          if (numOfSettledPromise === promises.length) {
            resolve(results);
          }
        },
        (reason) => {
          results[i] = {
            status: 'rejected',
            reason,
          };

          numOfSettledPromise++;
          if (numOfSettledPromise === promises.length) {
            resolve(results);
          }
        }
      );
    });
  });
}

Example Usage

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise 1 resolved");
  }, 1000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("Promise 2 rejected");
  }, 2000);
});

const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise 3 resolved");
  }, 3000);
});

PromiseAllSettled([promise1, promise2, promise3]).then((results) => {
  console.log(results);
})

// output 
[
  { status: 'fulfilled', value: 'Promise 1 resolved' },
  { status: 'rejected', reason: 'Promise 2 rejected' },
  { status: 'fulfilled', value: 'Promise 3 resolved' } 
]

Use Cases

  1. Handling Multiple Outcomes:

    • When you need to perform multiple asynchronous operations and handle each result individually, regardless of whether they succeed or fail.
  2. Ensuring All Promises Settle:

    • When you want to ensure that all promises have settled before proceeding with further logic, useful in scenarios like cleaning up resources or aggregating results.

By using Promise.allSettled, developers can manage multiple asynchronous operations and handle each outcome in a comprehensive manner, ensuring that all results are processed, whether the promises are fulfilled or rejected.