codecks.

Async & promises · Output question

JavaScript Promise.all result order

Promises finish at different times. Predict how Promise.all orders the values passed to its reaction.

const slow = new Promise(resolve =>
  setTimeout(() => resolve("slow"), 0));
const fast = Promise.resolve("fast");
Promise.all([slow, fast]).then(values => {
  console.log(values.join(","));
});

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

  1. fast,slow
  2. slow,fast
  3. fast
  4. slow
Reveal the answer and execution trace
slow,fast

Promise.all keeps results in the input order, regardless of which promise fulfills first.

  1. Line 3. fast is fulfilled while slow still waits for its timer.
  2. Line 4. Promise.all waits until both inputs are fulfilled.
  3. Line 2. The timer eventually fulfills slow.
  4. Line 5. The collected array follows [slow, fast], so it logs "slow,fast".

Reference: Promise all ordering on MDN.