Everyone recommends using async (non-blocking) functions instead of sync functions in Node.js .
So whats the use of sync functions in node.js if they are not recommended?
For example : Why use fs.readFileSync()
if fs.readFile()
can do the same job without blocking?
A Synchronous function is a function that does not return until the work is completed or has failed. So all of the functions that we wrote for the last couple of days have been synchronous functions because that's how they work.
Sync is single-thread, so only one operation or program will run at a time. Async is non-blocking, which means it will send multiple requests to a server. Sync is blocking — it will only send the server one request at a time and will wait for that request to be answered by the server.
Synchronous JavaScript as the name implies, means in a sequence, or an order. Here, every function or program is done in a sequence, each waiting for the first function to execute before it executes the next, synchronous code goes from top to bottom.
NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications.
Sync functions are useful, especially on startup, where you want to make sure that you have the result prior to executing any more code.
For example, you could load in a configuration file synchronously. However, if you are trying to do a file read during a live request, you should use async functions so you don't block other user requests.
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