LoginSignup
18
18

More than 5 years have passed since last update.

Promiseでループ処理をする

Posted at

以前forループをPromiseで実装する方法の記事を書きましたが、別な方法で繰り返しを実装してみました。

問題

同期処理で以下のような処理の流れをPromiseを使った非同期処理に直したい。

while(true) {
  a();
  var result = b();
  if (result) {
    c();
  } else {
    d();
    break;
  }
}

console.log('done');

上のコードの中で、a(),b(),c(),d()がそれぞれPromiseを返す非同期処理になる想定です。

解答

上記while() { ... }のブロック全体が一つのPromiseになると考えて、こうしてみる。

var promise = (function loop() {
  return a()
    .then(b)
    .then(function(result) {

      if (result) {
        return c().then(loop);
      } else {
        return d();
      }

    });
})();

promise.then(function(){
  console.log('done');
});

再帰呼び出しは頭の体操になりますね。
Promiseはこういうのをもっと簡単に書けるようになるといいんだけどなぁ…

18
18
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
18
18