Open In App

Sequential Functionality in Node.js

Last Updated : 31 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

It is basically executing Asynchronous Tasks in series or synchronously. Java is Asynchronous in nature and so is the Node. Node handles multiple requests at the same time by using Event loop and callback functions. 

There are 2 methods to perform different asynchronous functions synchronously or sequentially: 

Using Callback function: It is the Event handler in the Node. This function is generally called at the completion of a given task.

Reading the files in parallel using callbacks required for a loop. In order to read a file sequentially, it requires a recursive function. This function checks if it has reached the last file. If so, it is completed otherwise it will continue reading the next file. 

The code for the following example is as follows:

  • The code is to read all the files in the folder in sequence using callbacks.
  • To read files in the folder, we will first have to see which files are in the folder.

Example 1: In this example, we will use the callback function.

javascript




// fs is a built in module to handle the file system
// Require function is used to include the module
// followed by module's name
const fs = require("fs");
 
// Start with readdir() function and wait for the
// operation to complete
fs.readdir("...", function (err, files) {
    if (err) {
 
        // Console.log is used to print the
        // result as it is
        console.log("Error in file contents.");
    }
    else {
 
        // It will start reading files from index 0
        let ttlBytes = 0;
 
        // This function repeatedly calls itself
        // until all the files are read
        let readFiles = function (index) {
            if (index == files.length) {
                console.log("Done reading all the files. ttlBytes = "
                    + ttlBytes);
            }
            else {
 
                // For each file we use readFile() to get
                // the contents of the file
                fs.readFile(files[index], function (err, data) {
                    if (error) {
                        console.log("Error reading the file", err);
                    } else {
                        ttlBytes += data.length;
                        readFiles(index + 1);
                    }
                });
            }
        };
        readFiles(0);
    }
});


Output:

Error in file contents.

Using Promises: It is a design pattern in Node.js to avoid the callback hell. These are introduced to reduce the complexity of Asynchronous JavaScript code. A promise has 3 states:

  • Pending: You don’t know if people will come to your birthday party or not.
  • Rejected: If the promise has been rejected it means people have refused to come to your birthday party.
  • Resolved: If the promise has been resolved it means people are ready to come to your birthday party.

The code for the following example is as follows:

 Example 2: In this example, we will use promises.

javascript




const arePeopleReady = true;
 
// Promise accepts executor function as argument
const invitationBirthday = new Promise((resolve, reject) => {
    if (arePeopleReady) {
        return resolve('People are ready to come to your Birthday party');
    } else {
        var reason = new Error('People are not Ready');
        return reject(reason);
    }
});
 
// Call our promise
const askPeople = () => {
    invitationBirthday
        .then((fulfilled) => {
 
            // Awesome!, People have accepted your invitation
            console.log(fulfilled);
        })
        .catch(error => {
 
            // Hard luck, people are not ready
            console.log(error.message);
        });
}
askPeople();


Output:

People are ready to come to your Birthday party

Other design methods to avoid callback-hell in Node.js are as follows:

  • Execute Tasks In Series Using Async.series.
  • Execute tasks In Series Using Async/Await.
  • Execute Tasks In Series Using Async.waterfall.

Using Async/Await: An example of Async/Await can be shown as follows:

  • Here in this example, we are not using rejections/errors just for the sake of simplicity
  • Async functions return a Promise
  • If the function shows an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved.

Example 3:  In this example, we will use Async/Await.

javascript




// A function is created that accepts only one parameter
// Resolve method is called on this promise
// setTimeout is used to simulate a blocking Async operation
const x=2
function addIntAfter4Seconds(x) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(x + 4);
        }, 2000);
    });
}
// Await expression will pause the async function
// and wait for the promise to resolve before moving forward
// addAsync is used to set up a promise chain
async function addAsync(x) {
    const a = await addIntAfter4Seconds(10);
    const b = await addIntAfter4Seconds(20);
    const c = await addIntAfter4Seconds(30);
    return x + a + b + c;
}
 
// then method to conclude the logic
// the returned value is logged to the console
addAsync(x).then((sum) => {
    console.log(sum);
});


Output:

74


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads