Middle+
Tell me about Promise: what it is, states, and static methods (especially the difference between Promise.all and Promise.race)?
sobes.tech AI
Answer from AI
Promise is an object in JavaScript representing the result of an asynchronous operation that can either succeed or fail.
States of a Promise:
- pending — initial state, operation not completed.
- fulfilled — operation successfully completed.
- rejected — operation failed.
Static methods:
-
Promise.all(iterable)— takes an array of promises and returns a new promise that:- resolves when all promises in the array are fulfilled,
- or rejects immediately if any promise is rejected.
-
Promise.race(iterable)— returns a promise that settles as soon as the first promise in the array settles (fulfilled or rejected).
Example:
const p1 = new Promise(resolve => setTimeout(() => resolve('p1'), 100));
const p2 = new Promise(resolve => setTimeout(() => resolve('p2'), 200));
Promise.all([p1, p2]).then(results => console.log('All:', results)); // Waits for both promises
Promise.race([p1, p2]).then(result => console.log('Race:', result)); // Waits for the first to settle
Thus, Promises simplify working with asynchronous code, allowing for more understandable and manageable execution flow.