I wanted to understand at which point an async js function was appended to the event loop and when it was being immediately executed:
async function test2(){
console.log('3 test2 is being executed');
}
async function test(){
console.log('2 test is being executed');
await test2();
console.log('4 test 2 was awaited');
}
console.log('1 test is about to be called');
test();
console.log('5 test was called');
Originally, I assumed that no matter if a function had any actual async functions happneing (setTimeout, fetch, loadFile, etc), the function would always be appended to the event loop if it was declared async.
So by that logic expected the order of console logs like this:
1 test is about to be called
5 test was called
2 test is being executed
3 test2 is being executed
4 test 2 was awaited
So I assumed, async function that don't have any actual real async functions in them always get executed immediately, leading to this order:
1 test is about to be called
2 test is being executed
3 test2 is being executed
4 test 2 was awaited
5 test was called
But instead I get this:
1 test is about to be called
2 test is being executed
3 test2 is being executed
5 test was called
4 test 2 was awaited
This means the order of execution is:
test is called test is being immediately executed (despite being marked async) test2 is being immediately executed (same as test) after test2 is being run, control is returned to line 14 (which means the event loop must have done something after all) finally, test reports that test2 was executed.
Can somebody explain this to me? How can it be that async functions sometimes get thrown onto the event loop and sometimes not? I this predictable and when?
Also if you remove the await, the order is 1 2 3 4 5.
I'd just like to understand what's the logic here.
EDIT: If the await keyword is the linchpin, why does this result in the same execution order?
async function test2(){
console.log('3 test2 is being executed');
}
async function test(){
console.log('2 test is being executed');
await test2();
console.log('4 test 2 was awaited');
}
console.log('1 test is about to be called');
let a=async ()=>{
await test();
}
a();
console.log('5 test was called');
1 test is about to be called
2 test is being executed
3 test2 is being executed
5 test was called
4 test 2 was awaited
An async
function always executes synchronously till the first await
. Execution continues when the awaited Promise settles. An async
function always returns a Promise, even if there is no await
inside it. Even if a Promise is resolve(…)
d synchronously, its settlement is always deferred to a job.
In both examples the asynchronous events are the settlements of the implicit Promises created by returning from test2
and test
.