Skip to content

Instantly share code, notes, and snippets.

@ischenkodv
Created August 8, 2015 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ischenkodv/194e65f775c372fc012f to your computer and use it in GitHub Desktop.
Save ischenkodv/194e65f775c372fc012f to your computer and use it in GitHub Desktop.
var fs = require('fs');
var files = ['foo.txt', 'bar.txt', 'baz.txt'];
var promises = [];
for (var i = 0; i < files.length; i++) {
promises.push(readFile(files[i]));
}
Promise.all(promises).then(function(results) {
// results - array with 3 text elements.
console.log('results', results);
}).catch(function(error) {
console.log('error', error);
});
function readFile(name) {
return new Promise(function(resolve, reject) {
var result = '';
var stream = fs.createReadStream(name, {encoding: 'utf8'}).on(
'readable',
function(s) {
var buf;
while ((buf = stream.read()) !== null) {
result += buf;
}
}
).once('end', function() {
resolve(result);
}).once('error', function(error) {
reject(error);
});
});
}
@Globik
Copy link

Globik commented Aug 9, 2015

Очень изящно. Благодарствую!

@frontLord
Copy link

Promise is not defined

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