Asynchronous Functions and Callbacks

Synchronous functions executes one after the other and they are executed in the order in which they appear in the program. Synchronous functions are blocking, in the sense that it blocks resources until it finishes. It would be inefficient to perform certain operations like file read, http request, database query etc., synchronously.

Asynchronous functions can be executed in parallel. That means after the asynchronous function is called, the program resumes execution and does not wait for the asynchronous function to finish. The lines of code that comes after the async function are executed immediately. This means that there should be some reliable way of returning results from an asynchronous function without messing up the flow of control.

One method is to use callbacks. Asynchronous functions can take another function as argument. The function passed as the argument is called a callback. When the async function finishes execution, it calls the callback function. It also passes its results as arguments to the callback function.

Node.js built-in functions are mostly asynchronous, but many have synchronous variants. Consider the fs.readFile() method from filesystem(fs) module. The syntax is

fs.readFile( file, options, callback)
var fs = require('fs');
fs.readFile('abc.txt', 'utf-8',function (err, data) {
  if (err)
    return console.log(err);
  console.log(data);
});

The callback function is

function (err, data) {
  if (err)
    return console.log(err);
  console.log(data);
}

If the readFile() function fails, it populates the err variable. Otherwise it passes the file's contents as the data variable. The fs.readFile() method's synchronous counterpart is fs.readFileSync().

While working with async code, you could end up with several nested async functions and it could lead to a callback hell. There are packages such as async that help to organize the flow of control when working with asynchronous functions. There is also an approach that uses Promise objects to improve the structure of asynchronous code.


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.