Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 681
Isaac Krementsov Avatar asked Aug 16 '19 16:08

Isaac Krementsov


2 Answers

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.

like image 119
Aritra Chakraborty Avatar answered Nov 11 '22 02:11

Aritra Chakraborty


The reason you shouldn't use *Sync functions is that they block the event loop. That causes your application to become irresponsive while synchronous functions are being executed.

Promises help you avoid the callback hell problem when you are dealing with async code. Additionally, async/await syntax allows you to write asynchronous code that LOOKS like synchronous code. So it's perfectly fine to use async and await.

like image 39
fardjad Avatar answered Nov 11 '22 03:11

fardjad