Which is better, async or sync, for a sync work flow ( NODE JS ) ? | Sololearn: Learn to code for FREE!

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 !!!

3/21/2022 2:08:24 PM

Abhay

2 Answers

New Answer

+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

-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.