Skip to content

Instantly share code, notes, and snippets.

@goofmint
Created September 6, 2017 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goofmint/5001fbbcd67c72d8753146c1ab00f691 to your computer and use it in GitHub Desktop.
Save goofmint/5001fbbcd67c72d8753146c1ab00f691 to your computer and use it in GitHub Desktop.
// ループ処理の完了を受け取るPromise
new Promise(function(res, rej) {
  // ループ処理(再帰的に呼び出し)
  function loop(i) {
    // 非同期処理なのでPromiseを利用
    return new Promise(function(resolve, reject) {
      // 非同期処理部分
      setTimeout(function() {
        console.log(i);
        // resolveを呼び出し
        resolve(i+1);
      }, 100);
    })
    .then(function(count) {
      // ループを抜けるかどうかの判定
      if (count > 10) {
        // 抜ける(外側のPromiseのresolve判定を実行)
        res();
      } else {
        // 再帰的に実行
        loop(count);
      }
    });
  }
  // 初回実行
  loop(0);
}).then(function() {
  // ループ処理が終わったらここにくる
  console.log("Finish");
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment