async.map()

Let's have a look at an example where async shines and is able to remove unnecessary code. The following example shows how we call the fs.stat() method that will asynchronously tell us about a file, such as its size, when it was created, and so on. A normal call fs.stat() would look like this:

// async-demo/app.js

const fs = require('fs');

const basePath = __dirname + '/files/';
const files = ['file1.txt', 'file2.txt', 'file3.txt'];

fs.stat(basePath + 'file1.txt', (err, result) => {
if(err) {
console.log('err');
} else {
const { size, birthtime } = result;
console.log('Size',size);
console.log('Created', birthtime);
}
});

What if we wanted to make several calls and wanted to know the stats of several files? Firing off a number of calls- one per file- would mean our calls would come back at different times, depending on the size of the file. What if we don't care about the response until everything comes back? This is what the async library can help us with. There is a map() function that will allow us to fire off several calls at once and only return once all the calls are done, like so:

// app-map.js

const async = require('async');
const fs = require('fs');
const basePath = __dirname + '/files/';
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
const mappedFiles = files.map( f => basePath + f);

async.map(mappedFiles, fs.stat,(err, results) => {
if(err) {
console.log('error', err);
}else {
// looping through our results array
results.forEach(({size, birthtime}) => {
console.log('Size',size);
console.log('Created', birthtime);
});
}
});

So, what makes this so great? First off, our code aims to find out some file statistics about every file. Let's look at what life would look like without the async library:

// example of running a callback method in a forEach()

['file1','file2','file3'].forEach( f => {
var states = [];
fs.stat(f, (err, stat) => {
console.log('stat', stat);
states.push( stat );
})
})

We can see that we need to introduce a states array just to collect all the results and even then, we probably need to add some logic to know that we are on the last item in the array and can therefore start processing based on the fact that we now have all the results. Conversely, using async.map() means we have access to a function that collects the result in an array and also waits until the full array has been processed and all the results have come back.

So, the takeaway from all this is that async.map() helps us call a list of asynchronous calls into one call enabling us to process all the results once every single call is done, not before.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.181.89