Would async bar()
wait for sync foo()
to finish before awaiting the new promise/timeout and calling bar()
again?
function foo() {
console.log('is bar waiting for me to finish?');
}
async function bar() {
foo(); // is this blocking?
await new Promise((r) => setTimeout(r, 10));
await bar();
}
bar();
2
Answers
The short answer is "yes". I mean,
foo()
which is sync will blockbar()
execution untilfoo()
finishes. But, asbar()
is async, thenfoo()
will not block codes outside ofbar()
.Yes,
foo()
will complete before the await call withinbar()
.foo()
is synchronous, and JavaScript execution proceeds line by line within a synchronous function. The await keyword will only pause execution within the async functionbar()
afterfoo()
has already finished.You can verify this by adding (simulating) some delay.