LoginSignup
1
1

More than 5 years have passed since last update.

手っ取り早くPromiseでループ処理を書きたいとき

Last updated at Posted at 2018-08-28
function hoge() {
    // 非同期処理
}

for (var i = 0; i < 10; i++) {
    hoge(i); // 待ってくれない・・・
}

Promiseを使ってループ処理を書く場合はbluebirdなどを使うことが多いが、
今回は外部ライブラリを使わずにループ処理を書く方法を紹介する。

Promise Loop

for文やwhile文に対応する。

param name description
param1 callbackFn
param2 conditionFn return false to end loop
param3 incrementFn
promiseLoop.js
Promise.loop = function (callback, condition = () => true, increment = () => { }) {

    function onErr(resp) {
        errResp = resp;
        success = false;
        return false;
    }

    var errResp;
    var success = true;

    return (function loop() {
        return Promise.resolve(condition())
            .then((resp) => resp === false ? false : callback(), onErr)
            .then((resp) => resp === false ? false : increment(), onErr)
            .then((resp) => resp === false ? false : loop(), onErr);
    })().then(function () {

        if (success) {
            return;
        } else {
            throw errResp;
        }

    });

};

サンプル

sample1.js
var i = 0;
var max = 10;

Promise.loop(function () {
    return new Promise(function (resolve) {
        console.log(i);
        setTimeout(resolve, 1000);
    });
}, () => i < max, () => i++);

結果

console
0
1
2
3
~
99

Promise Each

Array.prototype.forEach()に対応する。

param name description
param1 array
param2 callbackFn(value, index, array) return false to end loop
promiseEach.js
Promise.each = function (array, callback) {

    var i = 0;
    var length = array.length;

    return Promise.loop(() => callback(array[i], i, array), () => i < length, () => i++);

};

サンプル

sample2.js
var array = ["a", "b", "c", "d"];

Promise.each(array, function (n, i) {
    return new Promise(function (resolve) {
        console.log(n);
        setTimeout(resolve, 1000);
    });
});

結果

console
a
b
c
d
1
1
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
1