Promise.allのシンプルなサンプルプログラムが見つからなかったので作ってみた。カレントディレクトリのファイルのファイルサイズの一覧を配列として表示する。
var fs = require('fs'),
Promise = require('promise');
fs.readdir('.', function(err, files){
Promise.all(files.map(function(file){
return new Promise(function(onFulfilled, onRejected){
fs.readFile(file, function(err, data){
if(err){
onRejected(err);
return;
}else{
onFulfilled(data.toString().length);
return;
}
})
});
})).then(function(res){
console.log(res);
}, function(err){
console.log("err", err);
})
})
参考文献
以下のリンクが役に立った。ただし、こちらのサンプルプログラムでは再起処理が入っているので、それを外してシンプルにPromise.allのサンプルとしてのがこの記事。