w3resource

Understanding Promise.allSettled in JavaScript


Promise.allSettled() Example:

Write a JavaScript program that takes an array of Promises and logs both resolved and rejected results using Promise.allSettled().

Solution-1: Basic Use of Promise.allSettled()

Code:

// Define multiple Promises
const promise1 = Promise.resolve("Resolved from promise1");
const promise2 = Promise.reject("Error from promise2");
const promise3 = Promise.resolve("Resolved from promise3");

// Use Promise.allSettled to handle both resolved and rejected results
Promise.allSettled([promise1, promise2, promise3])
  .then((results) => {
    results.forEach((result) => {
      if (result.status === "fulfilled") {
        console.log("Fulfilled:", result.value);
      } else if (result.status === "rejected") {
        console.log("Rejected:", result.reason);
      }
    });
  });

Output:

"Fulfilled:"
"Resolved from promise1"
"Rejected:"
"Error from promise2"
"Fulfilled:"
"Resolved from promise3"

Explanation:

  • Three Promises are defined:
    • promise1 resolves with a message.
    • promise2 rejects with an error.
    • promise3 resolves with another message.
  • Promise.allSettled() handles all the Promises and provides a detailed status report.
  • The results are iterated:
    • If status is "fulfilled", the resolved value is logged.
    • If status is "rejected", the rejection reason is logged.

Solution-2: Using Promise.allSettled() with Dynamic Promise Creation

Code:

// Function to simulate an asynchronous task
const asyncTask = (taskName, time, shouldReject = false) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldReject) {
        reject(`${taskName} failed`);
      } else {
        resolve(`${taskName} succeeded`);
      }
    }, time);
  });
};

// Create an array of dynamic Promises
const tasks = [
  asyncTask("Task 1", 1000),
  asyncTask("Task 2", 2000, true),
  asyncTask("Task 3", 1500)
];

// Use Promise.allSettled to handle the results
Promise.allSettled(tasks)
  .then((results) => {
    console.log("All tasks completed:");
    console.log(results);
  });

Output:

"All tasks completed:"
[[object Object] {
  status: "fulfilled",
  value: "Task 1 succeeded"
}, [object Object] {
  reason: "Task 2 failed",
  status: "rejected"
}, [object Object] {
  status: "fulfilled",
  value: "Task 3 succeeded"
}]

Explanation:

  • A helper function asyncTask creates asynchronous operations with customizable delay and rejection.
  • Three tasks are dynamically created:
    • Task 1 succeeds after 1 second.
    • Task 2 fails after 2 seconds.
    • Task 3 succeeds after 1.5 seconds.
    • Promise.allSettled() handles all the Promises and provides a summary of the results.
    • The complete results are logged as an array of objects with status and either value or reason.

See the Pen promises-and-async-await-exercise-5 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that uses Promise.allSettled() to process several API call simulations and categorizes the results into successes and failures.
  • Write a JavaScript function that applies Promise.allSettled() on an array of Promises that resolve or reject randomly.
  • Write a JavaScript function that aggregates the outcomes of mixed asynchronous tasks using Promise.allSettled() and returns a summary object.
  • Write a JavaScript function that demonstrates the use of Promise.allSettled() by processing immediate and delayed Promises together.

Go to:


PREV : Promise.any() Example.
NEXT : Simulating a Task Queue.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.