Background
This is a continuation of my previous post on async module in Node.js -
In the last post, we saw how neatly we can write code using async.waterfall. In this post, I will show you a similar trick with async.eachSeries method.
Without async
Let's consider the following scenario.
We get the type of events and we need to run them in a loop in order. Following is a sample code to do that -
And the output is -
/** * Program to demonstrate asyn nodejs module * @author : athalur */ const async = require("async"); var startDemo = function () { console.log("Starting Demo"); var events = ["Download", "Process", "Upload", "Del"]; events.forEach(event => { process(event, function () { console.log("Got callback for : " + event); }); }); console.log("Ending Demo"); } var process = function (processType, callback) { var processTime = 0; switch (processType) { case "Download": processTime = 2000; break; case "Process": processTime = 1000; break; case "Upload": processTime = 4000; break; case "Del": processTime = 100; break; } setTimeout(function () { console.log("Finished : " + processType); callback(); }, processTime); } startDemo();
And the output is -
Wait what happened here? We looped our events array in order -
- Download
- Process
- Upload
- Delete
But that did not clearly happen. Mostly because each process takes different time to finish. In a real-world scenario, it would mean it make API calls or disk IO, the time of which we cannot predict. Let's see how async comes to our rescue.
Change the main code as follows -
and rerun the code.
Now you can see all of them executed in a series.
NOTE1: async.forEach runs through the array in parallel, meaning it will run the function for each item in the array immediately, and then when all of them execute the callback (2nd argument), the callback function will be called (3rd argument).
NOTE2: async.eachSeries runs through the array in series, meaning it will run the function for each item in the array and wait for it to execute the callback (2nd argument) before going to next item and finally when all are done the callback function will be called (3rd argument).
var startDemo = function () { console.log("Starting Demo"); var events = ["Download", "Process", "Upload", "Del"]; async.eachSeries(events, function (event, callback) { process(event, callback); }, function(err){ if(!err){ console.log("Ending Demo"); } }); }
and rerun the code.
Now you can see all of them executed in a series.
NOTE1: async.forEach runs through the array in parallel, meaning it will run the function for each item in the array immediately, and then when all of them execute the callback (2nd argument), the callback function will be called (3rd argument).
NOTE2: async.eachSeries runs through the array in series, meaning it will run the function for each item in the array and wait for it to execute the callback (2nd argument) before going to next item and finally when all are done the callback function will be called (3rd argument).