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:

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.