Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()`.');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading