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

[Node.js]Promiseで再帰処理を使ってwhileっぽいループ処理を行う

Posted at

Promiseを使ったループ処理のサンプルはいくつかあるけど、
Promiseの結果を使ってwhileっぽく処理するやり方があまりなかったのでメモ。

変なところやもっといいやり方があればコメントください


function loopUnit() {
  return new Promise(resolve => {
    /* ループ処理本体 */
    resolve(result)
  })
}

function looper() {
  return new Promise(resolve => {
    // 永久ループにならないように限界条件を入れる (optional)
    if ( /* 限界条件 */) {
      resolve()
      return
    }

    // ループ処理
    loopUnit().then(result => {
      if ( /* while条件 */ ) {
        looper().then(() => resolve())
      } else {
        resolve()
      }
    })
  }) 
}

looper()
2
2
2

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