Sample code:
async function foo(i) {
await new Promise(resolve => setTimeout(resolve, 5000));
console.log('Completed foo', i);
}
async function bar(i) {
await new Promise(resolve => setTimeout(resolve, 5000));
console.log('Completed bar', i);
}
for (let i = 0; i < 10; i++) {
foo(i);
console.log('Fired', i);
await bar(i);
}
console.log('Done firing all async functions, unblocking...');
When I run this I get an error in the last line of the for loop indicating I can only await inside an async function.
Anyways, this question is to ask - when the for loop's 1st iteration is being executed, foo will immediately be added to the task queue. Then console log will run printing Fired. Then it will add bar to the task queue and await for the response. Hence block the for loop iterations until the bar execution completes.
At this point, Main thread is free. What is the behaviour in terms of whether foo or bar will be picked up from the task queue and put into the stack for execution by the main thread?