23. What is the difference between Promise.any and Promise.race in JavaScript?
hard
Promises are an essential part of asynchronous programming in JavaScript. They allow us to represent deferred values, perform operations on them, and execute multiple tasks simultaneously without blocking the main thread of execution. In this article, we will explore two methods for handling multiple promises: Promise.any and Promise.race.

Promise.any method:

Promise.any is an array method that takes an array of promises and returns a promise that resolves as soon as one or more of the promises in the array resolve. It allows us to execute multiple tasks simultaneously and wait for at least one of them to complete before proceeding.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Task 1'), 2000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Task 2'), 3000);
});

Promise.any([promise1, promise2]).then(results => console.log(results)); // ['Task 1']

In this example, we create two promises and pass them to Promise.any(). The resulting promise resolves as soon as one of the promises in the array resolves. If both promises resolve, the resulting promise resolves with an array containing all resolved values.

Promise.race method:

Promise.race is an array method that takes an array of promises and returns a promise that resolves or rejects as soon as one of the promises in the array resolves or rejects. It allows us to execute multiple tasks simultaneously and wait for the first promise to complete before proceeding.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Task 1'), 2000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => reject('Task 2 failed'), 3000);
});

Promise.race([promise1, promise2]).then(results => console.log(results)); // 'Task 1'

In this example, we create two promises and pass them to Promise.race(). The resulting promise resolves or rejects as soon as one of the promises in the array resolves or rejects. If both promises resolve, the resulting promise resolves with an array containing all resolved values.


So, in summary, Promise.any is used when we want to wait for at least one of multiple promises to complete before proceeding, while Promise.race returns a promise that resolves or rejects as soon as one of the promises in the array resolves or rejects. We can use both methods depending on our specific needs.