I wrote a code and try to come up with an expected answer to understand asynchronous behavior.
I numbered the console.log lines in a way I thought it should appear, but it printed line no. 6 before line no. 5
Actual output is:
I thought it would come as lines numbered in code. But line no. 5 and 6 are swapped in actual execution. can anyone explain why?
let waiter=async function (msg){
console.log('inside waiter before calling setTimeout 3')
setTimeout(()=>{
console.log('after 2 sec received: ',msg)
}, 2000);
console.log('inside waiter after calling setTimeout 4')
}
async function wrapper(){
console.log('wrapper before calling 2')
await waiter('Hi There')
console.log('wrapper after calling 5')
}
console.log('outside before calling 1')
wrapper();
console.log('outside after calling 6')
Because wrapper is asynchronous and you are not await-ing it for it to complete, code execution continues as normal, so 6 is logged before 5.
To have the 5 logged before 6, wait for wrapper to complete with await:
console.log('outside before calling 1');
await wrapper();
console.log('outside after calling 6');
The function that is calling wrapper must either return or await something in order for JavaScript to relinquish control of execution back to the event loop. The handler you provided to setTimeout is initiated by the event loop and that can't start executing until the function you're currently calling either returns or awaits.
Since you did not await the call to wrapper, this function just returns a promise, which you ignore / discard by not making use of the return value of wrapper(). And execution continues past it to your 6 waypoint before the timeout handler will execute.
If the function in which all your example code resides is async then you could do:
console.log('outside before calling 1');
await wrapper();
console.log('outside after calling 6');
If await is not available at that level, then you could use .then to have something be executed when the promise completes.
let waiter=async function (msg){
console.log('inside waiter before calling setTimeout 3')
setTimeout(()=>{
console.log('after 2 sec received: ',msg)
}, 2000);
console.log('inside waiter after calling setTimeout 4')
}
async function wrapper(){
console.log('wrapper before calling 2')
await waiter('Hi There')
console.log('wrapper after calling 5')
}
console.log('outside before calling 1');
wrapper().then(() => {
consolelog('promise returned by wrapper is now complete 6');
});
console.log('this will still happen before 5 (call it 4b)');