Sobes.tech
Junior — Middle

Could you explain what the Promise.allSettled method does in JavaScript?

sobes.tech AI

Answer from AI

The Promise.allSettled method in JavaScript takes an array of promises and returns a new promise that resolves when all the provided promises have settled — regardless of whether they were fulfilled or rejected.

Unlike Promise.all, which rejects as soon as one of the promises rejects, allSettled waits for all promises to settle and returns an array of objects with the results of each promise.

Each object in the array has the form:

  • { status: "fulfilled", value: ... } — if the promise was fulfilled
  • { status: "rejected", reason: ... } — if the promise was rejected

Example:

const promises = [
  Promise.resolve(1),
  Promise.reject('Error'),
  Promise.resolve(3)
];

Promise.allSettled(promises).then(results => {
  results.forEach(result => {
    if (result.status === 'fulfilled') {
      console.log('Success:', result.value);
    } else {
      console.log('Error:', result.reason);
    }
  });
});