6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsにおけるPromise.allの基本パターン

Last updated at Posted at 2014-07-28

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のサンプルとしてのがこの記事。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?