1
2

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.

Promiseを使ってループで直列実行する

Posted at

直列動作のサンプル

function PromiseMaker(i) {
    return function() {
      return new Promise(function(resolve, reject) {
        setTimeout(function(){ 
            console.log("i:" + i);
            resolve();
         }, 100);
      });
    }
};


var p = Promise.resolve();
for(var i=0; i < 15; i++) {
    p = p.then(PromiseMaker(i));
}

動作しないパターン

var p = Promise.resolve();
for(var i=0; i < 15; i++) {
    p.then(PromiseMaker(i));
}

後者が動作しない理由

p.thenが返すPromiseに対してthenを繋げなければいけないのに、
最初のPromiseに対してすべて繋がってしまっているので、
並列で実行されてしまうということでした。

参考: http://p-baleine.hatenablog.com/entry/2014/03/14/085536

こういった形が必要なければ、素直にawait/asyncやPromise.allを使う方が良いかもしれません…。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?