The performance question interviewers love
Two awaits in a row run sequentially: the second task does not even start until the first finishes. Two 100 ms tasks take 200 ms.
To run them in parallel, start both promises first (calling the function starts the work), then await:
const p1 = fetchA(); // work starts now const p2 = fetchB(); // this one too const [a, b] = await Promise.all([p1, p2]); // ~100 ms total
Promise.all(array) returns one promise that fulfills with an array of all results, in input order, once every input fulfills.
Code exercise · javascript
Run it. In the sequential half, A (40 ms) fully finishes before B (20 ms) even starts. In the parallel half, both start together, so the shorter D finishes first.
all is fail-fast, and the alternatives
Promise.allrejects as soon as any input rejects (fail-fast). Good when every result is required.Promise.allSettlednever rejects. It waits for everything and gives you{status, value | reason}per input. Good for "do as much as possible" jobs.Promise.racesettles with whichever input settles first, commonly used to add timeouts.
Rule of thumb to say out loud in interviews: awaits in a row when step 2 needs step 1's result, Promise.all when the tasks are independent.
Quiz
`const [a, b] = await Promise.all([slowTask, fastTask]);` — fastTask finishes first. What lands in `a`?
Quiz
You `Promise.all` five requests. The third one rejects after 10 ms while the others need 100 ms. What happens?
Code exercise · javascript
Your turn. Load users 1, 2 and 3 IN PARALLEL with `Promise.all` and print them joined by `, `. Sequential awaits would work but take 3× as long, so use all.