Sub topic 1
Recap: Pending, Fulfilled, Rejected
Prerequisites
This chapter assumes you know JavaScript functions, arrays and destructuring, then/catch, async/await, try/catch, and the basic idea of the event loop.
Promise States
A promise starts pending. It then settles exactly once, either fulfilled with a value or rejected with a reason. After it settles, its state never changes again.
Sequential Versus Concurrent
An await pauses the function until that promise settles. If you await independent tasks one after another, their waiting times add up. If you start every task first and then wait for all of them together, the total time is about as long as the slowest task.
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function sequential() { // about 300 ms
const a = await delay(100, 'a');
const b = await delay(200, 'b');
return [a, b];
}
async function concurrent() { // about 200 ms
return Promise.all([delay(100, 'a'), delay(200, 'b')]);
}
concurrent().then(console.log); // ['a', 'b']What a Combinator Does
A combinator takes an iterable of promises (or plain values) and returns one new promise. Each of the four combinators has its own rule for when that promise settles.
Promise.all
Promise.all fulfills when every input has fulfilled. Its value is an array of the results in input order, whatever order the inputs finished in. Plain values count as already fulfilled.
Promise.all([
Promise.resolve(1),
new Promise((resolve) => setTimeout(() => resolve(2), 50)),
3
]).then(console.log); // [1, 2, 3]Fail-Fast
As soon as any input rejects, Promise.all rejects with that reason and ignores every other result. The other operations do not stop. They keep running in the background.
const slow = new Promise((resolve) =>
setTimeout(() => { console.log('slow finished anyway'); resolve('slow'); }, 100)
);
Promise.all([slow, Promise.reject(new Error('boom'))])
.catch((err) => console.log(err.message)); // 'boom', then 'slow finished anyway'Exercise
Three fetches take 300 ms, 100 ms, and 200 ms. The 100 ms fetch rejects. When does Promise.all reject, and what happens to the other two fetches?
Show answer
It rejects at about 100 ms with that fetch's error. The other two fetches keep running until they finish, and their results are discarded.