Running asynchronous functions in series with promises

Viewed 1364

I am trying to run multiple asynchronous tasks in series using promises. Each task should run right after the previous one finishes. This is simplified example what I have tried:

var order = [];
var tasks = [
    new Promise(resolve => {
        order.push(1);
        setTimeout(() => {
            order.push(2)
            resolve();
        }, 100);
    }),
    new Promise(resolve => {
        order.push(3);
        setTimeout(() => {
            order.push(4)
            resolve();
        }, 100);
    }),
    new Promise(resolve => {
        order.push(5);
        resolve();
    })
];

tasks.reduce((cur, next) => cur.then(next), Promise.resolve()).then(() => {
    console.log(order); // [ 1, 3, 5 ]
});
setTimeout(() => console.log(order), 200); // [ 1, 3, 5, 2, 4 ]

I would expect order to be equal [ 1, 2, 3, 4, 5 ] in the callback function. However I got those strange results ([ 1, 3, 5 ] in then callback and [ 1, 3, 5, 2, 4 ] in delayed function). What am I missing?

4 Answers
Related