How to chain a variable number of promises in Q, in order?

There’s a nice clean way to to this with [].reduce.

var chain = itemsToProcess.reduce(function (previous, item) {
    return previous.then(function (previousValue) {
        // do what you want with previous value
        // return your async operation
        return Q.delay(100);
    })
}, Q.resolve(/* set the first "previousValue" here */));

chain.then(function (lastResult) {
    // ...
});

reduce iterates through the array, passing in the returned value of the previous iteration. In this case you’re returning promises, and so each time you are chaining a then. You provide an initial promise (as you did with q.resolve("start")) to kick things off.

At first it can take a while to wrap your head around what’s going on here but if you take a moment to work through it then it’s an easy pattern to use anywhere, without having to set up any machinery.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)