1

For example, require is synchronous.

If I put require in an async function and call that async function, does it block nodejs?

1
  • 2
    Async is cooperative multitasking; if you can't await it (or pass a callback), it's blocking. Commented Dec 1, 2019 at 19:22

2 Answers 2

2

If I put require in an async function and call that async function, does it block nodejs?

Yes, it does. If the module you are using require() to load is not already cached, then it will block the interpreter to load the module from disk using synchronous file I/O. The fact that it's in an async function doesn't affect anything in this regard.

async functions don't change blocking, synchronous operations in any way. They provide automatic exception handling and allow the use of await and always return a promise. They have no magic powers to affect synchronous operations within the function.

FYI, in nearly all cases, modules you will need in your code should be loaded at module initialization. They can then be referenced later from other code without blocking the interpreter to load them.

Sign up to request clarification or add additional context in comments.

3 Comments

What about import()? Will that also block io and the interpreter?
@DarrenRahnemoon - Yes, import is also synchronous and it blocks. Both import and require() in node.js are primarily designed for startup code when it would really, really, really complicate things if it was asynchronous.
I've been looking for this explanation for a while now. Thank you for clarifying. I have a rmSync call in an async function which I suspected was blocking the nodejs thread, and according to you it does :)
0

It will still block. This is true for whichever blocking code you would wrap in an async function. Also realise that using an async function is not useful unless you also use await in it.

You could for instance write the async function as follows:

async function work() {
    await null;
    synchronous_task();
}

work();
console.log("called work");

Here the call to work will return immediately, because of the await, but as soon as the code following that call has completed (until the call stack is empty), the execution will continue with what follows the await null, and will still block until that synchronous code has finished executing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.