I have two async
functions. Both of them are waiting for two 3 seconds function calls. But the second one is faster than the first. I think the faster one is running in parallel and other in serial. Is my assumption correct? If yes, why is this happening as both the functions look logically same?
function sleep() {
return new Promise(resolve => {
setTimeout(resolve, 3000);
});
}
async function serial() {
await sleep();
await sleep();
}
async function parallel() {
var a = sleep();
var b = sleep();
await a;
await b;
}
serial().then(() => {
console.log("6 seconds over");
});
parallel().then(() => {
console.log("3 seconds over");
});
setTimeout
is async? There's nothing async in your code except function declarations. – CleorasetTimeout
is by it's very nature asynchronous...and pretty much everything else in OP's code is asynchronous as well... – CourtyardsetTimeout
is not asynchronous at all. It's a synchronous function that tells the event loop to execute a function at a later time. It's a mechanism, there's absolutely NOTHING asynchronous in this code. Which two moving parts are moving at different speeds, in different execution contexts? Zero. Hence, this code isn't async at all. – CleorasetTimeout
, bothserial
andparallel
, and the callbacks to both calls to.then
, all run in different executing contexts. – CourtyardsetTimeout
is synchronous. Emulating the mechanism of async behaviour does not mean something is async. But hey, if you prefer to believe it is - I'm just a mere mortal telling you a story you don't like. – Cleora