Synchronous and Asynchronous communication

Node support both synchronous and asynchronous communication. What is the difference? Synchronous communication is sequential communication. You can only run one job at a time and all jobs need to wait for their turn to run. In asynchronous communication, the jobs can run in parallel depending on available resources. Following is a simplified example.

Suppose you call your Internet service provider and need to speak to a representative. You will be placed on hold until someone becomes available. This is synchronous communication. You are put on hold and you cannot do anything else. Some companies give you the option of a callback. You call in and leave a callback number. When a representative is free, he or she will call you back. You are free to do other things until you turn comes up. You are not on hold. This is asynchronous communication.

In asynchronous programming, a callback is equivalent of function. It is called after a task is completed.

Following code will synchronously list contents of a directory:

fh = require(‘fs’);
content = fh.readdirSync(‘mydirectory’);
console.log(content);

Following code will asynchronously list contents of a directory

fh = require(‘fs’);
content = fh.readdir(‘mydirectory’);
console.log(content);

Except for the function name, the rest is the same.