For example, require is synchronous.
If I put require in an async function and call that async function, does it block nodejs?
For example, require is synchronous.
If I put require in an async function and call that async function, does it block nodejs?
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.
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.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.