Skip to content

Instantly share code, notes, and snippets.

@dpastoor
Last active February 7, 2016 07:00
Show Gist options
  • Select an option

  • Save dpastoor/61e30055da08235f2fe1 to your computer and use it in GitHub Desktop.

Select an option

Save dpastoor/61e30055da08235f2fe1 to your computer and use it in GitHub Desktop.
example of async await for reading multiple files
let Promise = require('bluebird');
let fs = Promise.promisifyAll(require('fs')); // adds Async() versions that return promises
let path = require('path');
let _ = require('lodash');
/** Returns the number of files in the given directory. */
let countFiles = async function(dir) {
let files = await fs.readdirAsync(dir);
console.log(files);
let paths = _.map(files, (file) => path.join(dir, file));
console.log(paths);
let stats = _.map(paths, (path) => {
console.log('promise for async: ' + path)
return fs.statAsync(path).then(res => {
console.log('got result for ' + path);
return res.isFile()
})
}); // parallel!
let results = await Promise.all(stats);
// let results = await* stats --> this is the same as doing Promise.all but got a warning from babel that it could be deprecated?
return _.filter(results, (res) => res).length;
}
// Give it a spin
countFiles(__dirname)
.then (function (num) { console.log('There are ' + num + ' files in ' + __dirname); })
.catch(function (err) { console.log('Something went wrong: ' + err); });

babel-node async-await.js

[ 'node_modules', 'package.json', 'test-async-await.js' ]

[ '/Users/devin/Repos/js-scratch/async-await/node_modules',

'/Users/devin/Repos/js-scratch/async-await/package.json',

'/Users/devin/Repos/js-scratch/async-await/test-async-await.js' ]

promise for async: /Users/devin/Repos/js-scratch/async-await/node_modules

promise for async: /Users/devin/Repos/js-scratch/async-await/package.json

promise for async: /Users/devin/Repos/js-scratch/async-await/test-async-await.js

got result for /Users/devin/Repos/js-scratch/async-await/node_modules

got result for /Users/devin/Repos/js-scratch/async-await/package.json

got result for /Users/devin/Repos/js-scratch/async-await/test-async-await.js

There are 2 files in /Users/devin/Repos/js-scratch/async-await

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment