I\'m new to NodeJS. I have seen there are separate asynchronous and synchronous functions for the same task (ex: {fs.writeFile,fs.writeFileSync
} , {fs.read, f
Synchronous is a blocking call, where the thread is blocked until that call is over. Asynchronous is a non-blocking call, where the thread continues to execute the rest, why the call is executed separately.
Quoting from NodeJS Documentations:
Blocking is when the execution of additional JavaScript in the Node.js process must wait until a non-JavaScript operation completes. This happens because the event loop is unable to continue running JavaScript while a blocking operation is occurring.
Blocking methods execute synchronously and non-blocking methods execute asynchronously.
The use of Async methods Vs Sync methods:
If you call is an extensive operation like an I/O operation (Files, DB accesses etc), do use Async methods, because you don't want to block the entire process while and extensive operation is being carried out.
But if it is a regular call, where the result of it, is important for the rest of the process to function, do use Sync methods, where the process will halt until the call is completed.
If you are using AWS lambda for example, making an async call (will do the I/O operation asynchronously), might terminate the Lambda function as soon as the rest of the process is finished. So it is important identify when to use sync calls and async calls.
For more information, read the following doc.
Async:
Sync:
In reference to node.js fs.writeFile doc, it asynchronously writes data to a file. This means if you have following code:
1. some db operation
2. some non-related db operation
In such case, the 1st operation will not block 2nd operation. 2nd operation execute immediately after 1st(without waiting to finish)
However, there are some scenarios like:
1. some db operation
2. some related db operations(which you can't put in callbacks) and forcefully want to be after 1st operation.
Then use fs.writeFileSync.
The reason for having both sync and async verisons of those operations is that they can be time-consuming, and since node.js has a single-threaded main event loop, you do not under any circumstances want to block the event loop with slow synchronous function calls.
That is why everything is done using callbacks (or promises, vows, or what your particular taste in async stuff happens to be) instead. This way, you can have an event loop that just calls an async function and handle the result of the async function in a callback, when it happens to be done.
This is one of the major strengths of node.js, and one of the basic rules: "do not block the main event loop".