Search code examples
node.jsexpressmodel-view-controllerasync-awaitsingle-threaded

Is it a bad idea to use async/await in a Node/Express server?


I have a NodeJS/Express web app, where TypeOrm is used for many database functions. To avoid callback hell I usually use async/await to call and wait for database actions from my endpoint methods.
I've heard, however, that methods like fs.readFileSync should always be avoided, since they are blocking and will force all other requests to wait. Does this also apply to async/await? Do I have to use promises and callbacks to get decent multi-user performance?


Solution

  • Sync functions really BLOCK the event loop, until the io is complete. But in other hand async-await is just syntactic sugar to the Promise chaining. It is not actually synchronous, it just looks like it. That is the biggest difference you need to understand.

    But, Some problems are introduces with async-await making the promises too sequential.

    For example, two independent promises should be executed parallelly with Promise.all But when you use async-await you tend to do

    await func1();
    await func2();
    

    So, logically you may make bottleneck yourself. But syntactically it has no problems like Sync ones whatsoever.

    You can check out ES5 transpilation using Babel REPL, you may understand a little bit better.