asynchronous - Is a syncronous function call inside of async recursive function blocking in Javascript? - Stack Overflow

admin2025-05-01  0

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();
Share Improve this question edited Jan 2 at 20:05 justiceorjustus asked Jan 2 at 20:00 justiceorjustusjusticeorjustus 1,9652 gold badges20 silver badges46 bronze badges 2
  • 3 Code flow when bar() is called will continue synchronously into and out of foo() before waiting for the promise at the second line. – Pointy Commented Jan 2 at 20:02
  • 1 Yes. Declaring a function async has 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
Add a comment  | 

2 Answers 2

Reset to default 2

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();
转载请注明原文地址:http://anycun.com/QandA/1746099345a91655.html