LearnFrenzy
Sign in Take a free test

Async/Await · Async/Await Coding Problems · Question 2

Download files sequentially and in parallel with async/await in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Download three files first one by one with a for…of loop, then all at once with Promise.all, and report how many downloads ran at the same time in each case.

Solution
main.js
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let active = 0, peak = 0;
async function download(name, ms) {
  peak = Math.max(peak, ++active);
  await sleep(ms);
  active--;
  return `${name} ✓`;
}
const files = [["notes.pdf", 15], ["video.mp4", 25], ["code.zip", 10]];

(async () => {
  const one = [];
  for (const [name, ms] of files) one.push(await download(name, ms));
  console.log("sequential:", one.join(", "), "| at once:", peak);

  peak = 0;
  const all = await Promise.all(files.map(([name, ms]) => download(name, ms)));
  console.log("parallel:  ", all.join(", "), "| at once:", peak);
})();

Output Verified by running it on Node.js

sequential: notes.pdf ✓, video.mp4 ✓, code.zip ✓ | at once: 1
parallel:   notes.pdf ✓, video.mp4 ✓, code.zip ✓ | at once: 3

The results are identical, but the sequential loop takes the sum of the times (50 ms) while Promise.all takes the longest (25 ms) – all three run together.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links