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