Javascript promise loop

Posted by ExiaHuang on April 17, 2017

ES6 Native Promise Loop

ES6 Native Promise Loop
1
2
3
4
5
6
7
8
9
Promise.resolve(0).then(function loop(i) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log(i);
            resolve(i+1);
        }, 100);
    })
    .then(loop);
});

ES6 Native Promise while Loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function action(i) {
    console.log(i);
    return {
        done: i > 9,
        value: i+1
    };
}

function loop(promise, fn) {
    return promise.then(fn).then(function(wrapper) {
        return !wrapper.done ? loop(Promise.resolve(wrapper.value), fn): wrapper.value;
    });
}

loop(Promise.resolve(0), action).then(function(value) {console.log('end: ' + value)});

One more example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function callFun(testclass){
    return new Promise(function (resolve, reject) {
      // Do some Async stuff
      // call resolve if it succeeded
      // reject if it failed
    });
}

Promise.resolve(0).then(function loop(i) {
    // The loop check
    if (i < arrayList.length) {              // The post iteration increment
        return callFun(arrayList[i]).then(function(){
            // console.log(i);
            return (i + 1);
        }).then(loop);
    }
}).then(function() {
    console.log('error', e);
}).catch(function(e) {
    console.log('error', e);
    appendError(e);
});