Course outline · 0% complete

0/27 lessons0%

Course overview →

Sequential vs parallel: Promise.all

lesson 6-2 · ~13 min · 15/27

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.

sequential: await a; await btask A (100 ms)task B (100 ms)= 200 msparallel: Promise.all([a, b])task A (100 ms)task B (100 ms)= 100 ms
Sequential awaits stack task times end to end. Starting both promises before awaiting overlaps them.

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.all rejects as soon as any input rejects (fail-fast). Good when every result is required.
  • Promise.allSettled never rejects. It waits for everything and gives you {status, value | reason} per input. Good for "do as much as possible" jobs.
  • Promise.race settles 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.