Sequential Functionality in Node

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:
1. 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 all files are in the folder.

Example #1

filter_none

edit
close

play_arrow

link
brightness_4
code

// fs is a built in module to handle the file system
// Require function is used to include the module
// followed by module's name
var 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
        var ttlBytes = 0;
  
        // This function repeatedly calls itself
        // until all the files are read
        var 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);
   }
});

chevron_right


2. 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 promise has been rejected it means people have refused to come to your birthday party.
  • Resolved: If 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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();

chevron_right


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.

3. 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
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);
});

chevron_right


OUTPUT:

82


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.