goliardico goliardico - 4 months ago 19
Node.js Question

Serial Execution of Promise

I would like to execute a function with a parameter looping from an array of values. Every execution must waits the previous to be completed.
The example code below should print:

Done: 1
Done: 2
Done: 3
Done: 4
Done: 5


Thanks!

p.

'use strict';

function f1(value) {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log('Done: ' + value);
resolve(true)
}, Math.random() * 2000 + 1000);
});
}

const vs = [0,1,2,3,4,5];

vs.reduce((start, next) => {
return f1(next)
})

Answer

If you want just ES6, try this:

'use strict';

function f1(value) {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            console.log('Done: ' + value);
            resolve(true)
        }, Math.random() * 2000 + 1000);
    });
}

const vs = [0,1,2,3,4,5];

let promiseChain = vs.reduce((start, next) => {
    return start.then(() => f1(next));
}, Promise.resolve());

promiseChain.then(() => console.log('Done!'));

If you're interested in getting the values out of the resolutions, you can try this as well.

Comments