0

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)
})
goliardico
  • 65
  • 8
  • I made this using angularjs promises however exactly the same can be done with native. https://gist.github.com/ste2425/608b74d20504d526d2c08dd8fa76f675 – ste2425 Jul 08 '16 at 16:25

1 Answers1

4

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.

Community
  • 1
  • 1
dvlsg
  • 5,378
  • 2
  • 29
  • 34