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();
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();
The short answer is "yes". I mean, foo() which is sync will block bar() execution until foo() finishes. But, as bar() is async, then foo() will not block codes outside of bar().
const delay = 3000; // 3 seconds of delay.
function foo() {
console.log('Is bar waiting for me to finish?');
console.log('Answer: Yes!');
}
async function bar() {
await new Promise((r) => setTimeout(r, delay)); // waits `delay` and `foo()`.
foo(); // is this blocking? r: yes
await new Promise((r) => setTimeout(r, delay)); // waits `delay` and loop.
await bar(); // loops.
}
// Will not block the lines that follows:
bar();
// Unblocked line.
console.log('I am not blocked by `bar()`.');
Yes, foo() will complete before the await call within bar(). foo() is synchronous, and JavaScript execution proceeds line by line within a synchronous function. The await keyword will only pause execution within the async function bar() after foo() has already finished.
You can verify this by adding (simulating) some delay.
function foo() {
console.log('is bar waiting for me to finish?');
let start = Date.now();
while (Date.now() - start < 5000) {} // Simulate delay
console.log('foo finished');
}
async function bar() {
console.log('calling foo');
foo();
console.log('foo returned');
await new Promise((r) => setTimeout(r, 10));
console.log('timeout finished');
// Preventing infinite recursion, just for testing
//await bar();
}
bar();

bar()is called will continue synchronously into and out offoo()before waiting for the promise at the second line. – Pointy Commented Jan 2 at 20:02asynchas no effect on how the code inside it runs. It's just syntactic sugar for wrapping a promise around the body. – Barmar Commented Jan 2 at 20:03