I understand the concept of single thread, micro task queue, macro task queue and event loop.
I also know that when an async function is called without the await keyword then the main thread doesn't block waiting for reponse whereas when the async function is called with await keyword then the main thread does block. In both cases the async function is added to task queue.
Today I came across a nested async function example (see code below) where-in the main thread doesn't block in the for loop's 1st iteration even though the function invoked has the await keyword on the nested async function.
It appears that calling an async function, whether nested or not, immediately puts the function into the task queue without checking what code is inside the async fucntion (that is - whether there is await or not)?
In other words - the main thread doesn't enter the child function foo
if the parent is not awaited?
Why does the await in the foo not block the for loop where as the await foo.. in the for loop would have blocked the loop?
async function foo(i) {
await new Promise(resolve => setTimeout(resolve, 5000));
console.log('Completed', i);
}
for (let i = 0; i < 10; i++) {
foo(i);
console.log('Fired', i);
}
console.log('Done firing all async functions, unblocking...');