javascriptasynchronousrecursionpromise

Is a syncronous function call inside of async recursive function blocking in Javascript?


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();

Solution

  • 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()`.');