10
9

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を使ったforループ

Last updated at Posted at 2014-12-16

こんな感じのループ処理をPromiseでやりたい。

for (var i = 0; i < 10; i++) {
  console.log(i);
}
console.log('END!!!');

関数を作ってみた。

function loop(init, condition, callback, increment) {
  return new Promise(function(resolve, reject) {
    init().then(function _loop() {
      condition().then(function(result) {
        if (result)
          callback().then(increment).then(_loop, reject);
        else
          resolve();
      }, reject);
    }, reject);
  });
}

init, condition, callback, incrementはそれぞれ全てPromiseを返す関数として実装します。
同期処理的に書くとこんな感じ。

for (init(); condition(); increment()) {
  callback();
}

使い方

var i;
loop(function() {
  return new Promise(function(resolve, reject) {
    i = 0;
    resolve();
  });
}, function() {
  return new Promise(function(resolve, reject) {
    resolve(i < 10);
  });
}, function() {
  return new Promise(function(resolve, reject) {
    console.log(i);
    resolve();
  });
}, function() {
  return new Promise(function(resolve, reject) {
    i++;
    resolve();
  });
}).then(function() {
  console.log('END!!!');
});

上記の例ではresolveしか呼んでませんが、ループ途中で例外を投げたりrejectを呼ぶと処理を中断してループを抜け、loop関数が返したPromiserejectedになります。

うーんもっと簡単に書けないかなぁ…

return new Promiseは固定なのでloopの中に入れるという手もある。ただPromiseをどうやって生成するかはプログラマ側に任せたほうが良いかもしれない。Promise対応ライブラリの呼び出しということもありうるし。

10
9
1

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
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?