Tell me about Promise: statuses, static methods (all, allSettled, any, race).
sobes.tech AI
Answer from AI
Promise is an object in JavaScript that represents the result of an asynchronous operation, which may be available now, later, or never.
Promise statuses:
- pending — initial state, operation not yet completed.
- fulfilled — operation successfully completed, result is available.
- rejected — operation finished with an error.
Static methods of Promise:
-
Promise.all(iterable)— takes an array (or other iterable) of promises and returns a new promise that:- resolves when all promises in the array are fulfilled,
- or rejects if any promise is rejected.
-
Promise.allSettled(iterable)— returns a promise that resolves when all promises have settled (regardless of outcome), and returns an array of objects with the results of each promise (status and value or reason). -
Promise.any(iterable)— returns a promise that resolves as soon as any of the promises fulfills. If all promises are rejected, it returns an AggregateError. -
Promise.race(iterable)— returns a promise that settles as soon as the first promise in the array settles (fulfilled or rejected).
Example of using Promise.all:
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3])
.then(values => console.log(values)) // [1, 2, 3]
.catch(error => console.error(error));