Sobes.tech
Middle

What other Promise API methods do you know besides Promise.all?

sobes.tech AI

Answer from AI

In addition to Promise.all, the Promise API has several useful methods:

  • Promise.race(iterable) — returns a promise that settles as soon as one of the promises in the iterable settles, whether fulfilled or rejected.

  • Promise.allSettled(iterable) — returns a promise that fulfills when all of the promises in the iterable have settled, with an array of objects describing the outcome of each promise.

  • Promise.any(iterable) — returns a promise that fulfills as soon as any of the promises in the iterable fulfills; if all promises are rejected, it rejects with an AggregateError.

Example of using Promise.race:

const p1 = new Promise(resolve => setTimeout(() => resolve('First'), 500));
const p2 = new Promise(resolve => setTimeout(() => resolve('Second'), 100));

Promise.race([p1, p2]).then(result => console.log(result)); // Will output 'Second'