Is async.each working as asynchronous array iterating?
Is async.eachSeries working as synchronous array iterating?(it waits response actually)
I'm asking these because both have callbacks but async.each works like asynchronous array iterating for ex:
//This is traditional way to iterate an array with callback functions in node.js
//Is this same with async.each ? i want to know it actually.
for (var i = 0; i < data.length; i++) {
(function (i) {
request(data[i],function(body){
console.log(body)
});
})(i);
//if this codes and async.each are doing same things ,
//i know that async gives me an aert when all finished thats the difference.
The difference can be explained with a simple example.
Consider we have 3 files
1.txt, 2.txt, 3.txt
. In which we have the contents for file2.txt
which is around 1GB size all other files are simple file with some minimum file size.A
1GB
file can be generated with the following command inlinux/unix
Create a 1GB file for file
2.txt
dd if=/dev/zero of=2.txt count=1024 bs=1024
The directory structure used
Do the required npm installs and try each of this code differently.
For AsyncEachSeries
The output will be
For AsyncEach
Output will be
Your code example is most similar to what
async.each
does, as all the asyncrequest
calls are made at once and allowed to proceed in parallel.The difference with
async.eachSeries
is that each iteration will wait for the async operation to complete before starting the next one.async.eachSeries() applies an asynchronous function to each item in an array in series.
For example, say you have a list of users, each of which needs to post its profile data to remote server log. Order matters in this case because the users in your array are sorted.
async.each() applies an asynchronous function to each item in an array in parallel.
Since this function applies iterator to each item in parallel, there is no guarantee that the iterator functions will complete in order.