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);
})();
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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!