Sobes.tech
Junior — Middle

Milline on erinevus Promise.all ja Promise.any funktsioonide vahel lubaduste töötlemisel?

sobes.tech AI

Vastus AI-lt

Promise.all accepts an array of promises and returns a new promise that:

  • resolves when all promises in the array successfully complete, returning an array of results in the same order;
  • rejects if at least one promise is rejected, immediately with that promise's error.

Promise.any accepts an array of promises and returns a promise that:

  • resolves as soon as any of the promises successfully completes, returning that promise's result;
  • rejects if all promises are rejected, returning an AggregateError containing all errors.

Example:

const p1 = Promise.reject('Error 1');
const p2 = Promise.resolve('Success 2');
const p3 = Promise.resolve('Success 3');

Promise.all([p1, p2, p3])
  .then(console.log) // will not be called
  .catch(console.error); // will log 'Error 1'

Promise.any([p1, p2, p3])
  .then(console.log) // will log 'Success 2'
  .catch(console.error);