JavaScript Interview Question #88

What is the difference between Promise.race() and Promise.any()?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

Promise.race settles as soon as the first input Promise settles, whether that first result is fulfillment or rejection. Promise.any fulfills as soon as any input fulfills and ignores earlier rejections while a possible fulfillment remains.

Detailed Explanation

Promise.race settles as soon as the first input Promise settles, whether that first result is fulfillment or rejection. Promise.any fulfills as soon as any input fulfills and ignores earlier rejections while a possible fulfillment remains.

If every input to Promise.any rejects, it rejects with an AggregateError. The two methods therefore solve different requirements: first settled result versus first successful result.

Code Example

const firstSettled = await Promise.race([
    requestA(),
    requestB()
]);

const firstSuccessful = await Promise.any([
    serverA(),
    serverB(),
    serverC()
]);