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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With