Reputation: 59
For example, require
is synchronous.
If I put require in an async function and call that async function, does it block nodejs?
Upvotes: 1
Views: 2689
Reputation: 707396
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.
Upvotes: 2
Reputation: 350280
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.
Upvotes: 0