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 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.