Skip to main content

More promise API

Promise.all

This API will allow us to take in an iterable, an array of promises and return a new promise.

That returned promise will only be resolved when all listed promises are resolved, the array of their results will become the result of this returned promise.

If any of the promises is rejected, the promise returned by Promise.all immediately rejects with that error

let promise = Promise.all(iterable);

// Example
Promise.all([
  new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
  new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
  new Promise(resolve => setTimeout(() => resolve(3), 1000))  // 3
]).then(console.log);
Promise.allSettled

A less stricter version of Promise.all, it waits for all promises to settle, and regardless of the result.

let urls = [
  'https://api.github.com/users/iliakan',
  'https://api.github.com/users/remy',
  'https://no-such-url'
];

Promise.allSettled(urls.map(url => fetch(url)))
  .then(results => { // (*)
    results.forEach((result, num) => {
      if (result.status == "fulfilled") {
        alert(`${urls[num]}: ${result.value.status}`);
      }
      if (result.status == "rejected") {
        alert(`${urls[num]}: ${result.reason}`);
      }
    });
  });
Promise.race

Similar to Promise.all but waits only for the first settled promise and get its result or error

The first promise that is resolved will become the value.

Promise.any

Similar to Promise.any but waits for the first fulfilled promise. If all of the promises are rejected then the returned promise is rejected with Aggregateerror with all the promise error in its errors property.