0

Which is better, async or sync, for a sync work flow ( NODE JS ) ?

Suppose the client need to read a text file on the server. We have to ways to do that task :- 1. Use fs.readFile() ( an async function) with callbacks or async await then wait for reading and then send the response. 2. Use fs.readFileSync() then wait for reading and send response. I mean the 2nd one ( sync one ) is simpler Also both 1st and 2nd option are blocking the main thread because both are blocking the response for some time. So which one is better in this case ? Plzzz help me to understand !!!

21st Mar 2022, 2:08 PM
Abhay
Abhay - avatar
2 Réponses
+ 1
It is simple, 1. Sync : run the sync, when you are staring your server and needed to called one, e.g. loading a config file in the memory before server started listen to the port. 2. Aync : run the async one when one need to read file inside a request handler so it will not block other request from the client. Note :- Sync is faster than async in reading files, but blocking the main thread, so use it before using server starts listening to a port. Q. Which one is better ? Ans :- It depends on where you are using it, in a request handler, we need a non blocking async method so other clients don't have to wait for previous client response. sync method are more faster but useful when executed once or before the server starts handling client requests
7th Sep 2022, 5:57 PM
Abhay
Abhay - avatar
- 1
The async one isn't blocking the main thread. It appears like that, because you are choosing to wait. But sync one on the other hand will block the thread. With the async process, you can keep doing stuff in the main thread. I don't know the specifics of your code. But, I would personally go with the async solution. Shoving everything down to the main thread makes it feel laggy and unresponsive.
21st Mar 2022, 11:37 PM
Mustafa A
Mustafa A - avatar