I was reading this article, and wondering why in the first snippet the seconde wait()
waits the first wait()
to finish whereas in the seconde snippet two wait()
run async?
async function series() {
await wait(500);
await wait(500);
return "done!";
}
async function parallel() {
const wait1 = wait(500);
const wait2 = wait(500);
await wait1;
await wait2;
return "done!";
}
function wait(ms) {
return new Promise(r => setTimeout(r, ms));
}
In your first function:
async function series() {
await wait(500); // 1
await wait(500); // 2
return "done!";
}
You're telling JS to await the first wait
as soon as it's started.
This means the second wait(500)
can't start, before the first one finishes:
wait(500) // 1
wait(500) // 2
In the second function:
async function parallel() {
const wait1 = wait(500); // 1
const wait2 = wait(500); // 2
await wait1;
await wait2;
return "done!";
}
Both wait
calls are started, before the code is told to await the results.
wait(500) // 1
wait(500) // 2
wait1
to pass,wait2
to passBecause wait1
and wait2
are triggered immediately after each other, they're practically running in parallel.
Imagine this:
If 2 people both start a stopwatch at the same time, if you need to wait before each stopwatch reaches 10 seconds, you still only have to wait 10 seconds.
In the series
function, on the other hand, the second stopwatch can't start before the first one finishes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With