skip to Main Content

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


  1. 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()`.');
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search