Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why use sync functions node.js

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?

like image 736
Flake Avatar asked Nov 10 '15 18:11

Flake


People also ask

What are sync functions?

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.

What is the difference between async and sync js?

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.

What is sync function in JavaScript?

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.

Is node JS sync or async?

NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications.


1 Answers

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.

like image 62
TbWill4321 Avatar answered Oct 12 '22 17:10

TbWill4321