w3resource

JavaScript Promise.any Explained with simple examples


Promise.any() Example:

Write a JavaScript function that takes multiple Promises and resolves with the first successful result using Promise.any().

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

Code:

// Define multiple Promises
const promise1 = new Promise((resolve, reject) => setTimeout(reject, 1000, "Error in promise1"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 500, "Success from promise2"));
const promise3 = new Promise((resolve) => setTimeout(resolve, 2000, "Success from promise3"));

// Use Promise.any to resolve with the first successful result
Promise.any([promise1, promise2, promise3])
  .then((result) => {
    console.log("First successful result:", result); // Logs: "Success from promise2"
  })
  .catch((error) => {
    console.error("All promises rejected:", error);
  });

Output:

"First successful result:"
"Success from promise2"

Explanation:

  • Three Promises are defined:
    • promise1 rejects after 1 second.
    • promise2 resolves successfully after 0.5 seconds.
    • promise3 resolves successfully after 2 seconds.
  • Promise.any() is used to resolve with the first successful result.
  • Since promise2 resolves first, its result is logged: "Success from promise2".
  • If all Promises reject, the .catch() block logs the AggregateError.

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

Code:

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

// Use Promise.any with dynamically created Promises
const tasks = [
  asyncTask("Task 1", 1000, true), // Rejects
  asyncTask("Task 2", 500),        // Resolves
  asyncTask("Task 3", 1500)        // Resolves
];

Promise.any(tasks)
  .then((result) => {
    console.log("First successful result:", result); // Logs: "Task 2 completed"
  })
  .catch((error) => {
    console.error("All tasks failed:", error);
  });

Output:

"First successful result:"
"Task 2 completed"

Explanation:

  • A helper function asyncTask simulates asynchronous operations with configurable delay and success/failure behavior.
  • The tasks array contains Promises generated using asyncTask:
    • Task 1 rejects after 1 second.
    • Task 2 resolves after 0.5 seconds.
    • Task 3 resolves after 1.5 seconds.
  • Promise.any() is used to handle the Promises and resolve with the first successful task result.
  • "Task 2 completed" is logged because Task 2 resolves first.

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


Improve this sample solution and post your code through Disqus

Previous: Effective error handling in JavaScript Promises.
Next: Understanding Promise.allSettled in JavaScript.

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.