Sequential Functionality in Node.js - GeeksforGeeks

14 Oct, 2021
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
// fs is a built in module to handle the file system// Require function is used to include the module// followed by module's namevar fs = require("fs");  // Start with readdir() function and wait for the// operation to completefs.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);   }});
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
const arePeopleReady = true;  // Promise accepts executor function as argumentconst 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 promiseconst 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();
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/AwaitAn 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
// A function is created that accepts only one parameter// Resolve method is called on this promise// setTimeout is used to simulate a blocking Async operationfunction 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 chainasync 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 consoleaddAsync(x).then((sum) => {  console.log(sum);});
OUTPUT:
82
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Express.js express.Router() Function
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript