According to google docs explanation of Async the following function named 'parallel' should execute in parallel, and the function named 'series' should execute sequentially.
Async Functions Explanation on Google Developers
Parallel should take 2 seconds to complete.
Series should take 4 seconds.
However, they both complete in 2 seconds.
Why doesn't series() take 4 seconds total? I am expecting the First timer to complete after 2 seconds, then the second timer to complete another 2 seconds later?
async function series() {
function timer(time) { setTimeout(function(){ console.log(`Hello ${time}`) }, time); }
await timer(2000); // Wait 2 seconds…
await timer(2000); // …should wait another 2 seconds
}
series() // should take 4 seconds to complete, but only takes 2 seconds
Why does this work in parallel but series does not work in series?
async function parallel() {
function timer(time) { setTimeout(function(){ console.log(`Hello ${time}`) }, time); }
let one = timer(2000); // Start a 2 second timer asynchronously…
let two = timer(2000); // …meaning this timer happens in parallel.
await one; // Wait 2 seconds for the first timer
await two; // …by which time this time finishes around same time
}
parallel() // completes in 2 seconds