DEV Community

Discussion on: Best Practices for ES2017 Asynchronous Functions (`async`/`await`)

Collapse
 
revenity profile image
Revenity

If I write like this:

const read = async path => fs.promises.readFile(path);
Enter fullscreen mode Exit fullscreen mode

Do Javascript block the process when I use await read()?

Collapse
 
somedood profile image
Basti Ortiz

Well, it does get "blocked" from the perspective of the caller who await-ed the read. That is, the caller gets paused at that point, thereby being "blocked".

However, since we're using the asynchronous fs.promises module, the runtime process itself (i.e. Node.js) is not blocked. As far as the event loop is concerned, Node.js will check if the file is available—in which case the promise resolves shortly after. Otherwise, it will periodically poll until the file is ready. In either case, the event loop continues to run, which is a good thing because this implies we may still poll and handle other promises and events for the meantime.

But if we use the synchronous APIs of the fs module instead (namely fs.readFileSync), that's when the event loop gets blocked. That is, no events will be polled and handled whatsoever. The loop is literally blocked until the requested file is ready.