Understanding the Concept of Callback

Callback is an asynchronous equivalent for a function that is called at the completion of a task. The Callback helps to avoid any I/O blocking and allows other code to execute in the period in-between. Node.js provides an Asynchronous platform that doesn’t wait for finishing the file I/O, which implies that Node.js uses Callbacks, making the Node.js platform highly scalable.

Blocking vs Non-Blocking

The operations that block any further execution until the current operation completes, are referred as Blocking. However, the operations that don’t block any execution are referred as Non-Blocking. As per the Docs of Node.js, the Blocking in Node.js happens when the execution of an additional JavaScript process waits until a Non-JavaScript process ends, which implies that Blocking methods works Synchronously; whereas Non-Blocking uses Asynchronous method with the help of Callback function.

Let’s see some examples given below that are based on the fundamental concept of Callback.

Blocking Example

File: blocking.js  

To execute the above program, type the following command on the terminal:

The Output is as follows:

Non-Blocking Example

File: non-blocking.js

To execute the above program, type the following command on the terminal:

The Output should is given as follows:

From the above script files and their outputs, we can conclude that the execution of code in the Blocking program is done in order. However, the execution of code in the Non-Blocking program is not done in a sequence. The execution of other codes doesn’t wait for the completion of the code to being executed.

Pin It on Pinterest

Share This