AI Hints
Home›JavaScript Tutorial›Promise.all and fetch
JavaScript · Lesson 85 of 138

Promise.all

Many at once.

⏱ 2 min read▶ Video at 1:42:40🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

If you await three slow jobs one after another, you wait for all three in a row. But if the jobs don't depend on each other, you can start them all at once, and wait for them together. That's much faster.

Promise.all
From the video: Promise.all
  • Awaiting in a row is slow
  • Independent jobs
  • Start them all together

One by one, or together

Each job takes three hundred milliseconds. Awaiting them in a row takes about nine hundred. Promise dot all starts all three together, and waits until every one is done, so it takes about three hundred. It gives back the results in the same order. Run it.

app.jsjavascript
const job = (name) =>
  new Promise(r => setTimeout(() => r(name), 300));

async function main() {
  let t = Date.now();
  await job("a"); await job("b"); await job("c");
  console.log("In a row:", Math.round((Date.now() - t) / 100) * 100, "ms");

  t = Date.now();
  const results = await Promise.all([job("a"), job("b"), job("c")]);
  console.log("Together:", Math.round((Date.now() - t) / 100) * 100, "ms");
  console.log(results);
}
main();
Output
In a row: 900 ms
Together: 300 ms
[ 'a', 'b', 'c' ]

Other combinators

Promise dot all rejects as soon as any job fails. Promise dot all settled waits for every job, and tells you which succeeded and which failed. Promise dot race gives you whichever settles first, which is handy for timeouts. And promise dot any gives the first success.

keyvalue
Promise.allall succeed, or fail fast
allSettledevery result, good or bad
racefirst to settle
anyfirst success

Summary

Promise dot all runs independent jobs at the same time and waits for them all. Next, getting data from a server with fetch.

Key takeaways
  • Start jobs together
  • await Promise.all([...])
  • Results in order
Next up: fetch — data from a server