I googled the question so many times but the only answer I see to this question is:
Async function always returns a promise
but nowhere have I found anything that answers when does that actually happen.
Is it as soon as it goes into the async function or as soon as it encounters the first await keyword?
I have just written this piece of code:
async function main() {
console.log(true);
let p = await new Promise(r => setTimeout(r, 2000, 100));
return p;
}
async function f() {
inner(await main())
function inner(d) {
console.log(d + 10)
}
console.log('done')
}
f();
The most important line is:
inner(await main())
main() will be executed first because of the higher priority a function call has in the precedence table and as async function returns a promise, it returns a pending promise!
But to return that, we must execute the main() first, so it goes into the main execution context and sees the console.log(true);
Now is that where the pending promise is returned by the main()?
Or it will log that and then it'll reach the await keyword and that's when it'll return a pending promise?
What if this was our code:
async function main() {
(function thatTakes30SecondsToFinish() {
// some time consuming task
}())
let p = await new Promise(r => setTimeout(r, 2000, 100));
return p;
}
Now in this case, will this main() in this line inner(await main()) immediately return a pending promise or it'll take 30 seconds before returning a pending promise?
Now my guess is:
This line inner(await main()) will immediately return a pending promise but the code inside main() will continue to execute until it gets to the first await keyword, is that correct?