How can I execute array of promises in sequential order?

jaaksarv picture jaaksarv · Nov 20, 2013 · Viewed 46.3k times · Source

I have an array of promises that need to run in sequential order.

var promises = [promise1, promise2, ..., promiseN];

Calling RSVP.all will execute them in parallel:

RSVP.all(promises).then(...); 

But, how can I run them in sequence?

I can manually stack them like this

RSVP.resolve()
    .then(promise1)
    .then(promise2)
    ...
    .then(promiseN)
    .then(...);

but the problem is that the number of promises varies and array of promises is built dynamically.

Answer

Esailija picture Esailija · Nov 20, 2013

If you already have them in an array then they are already executing. If you have a promise then it's already executing. This is not a concern of promises (I.E they are not like C# Tasks in that regard with .Start() method). .all doesn't execute anything it just returns a promise.

If you have an array of promise returning functions:

var tasks = [fn1, fn2, fn3...];

tasks.reduce(function(cur, next) {
    return cur.then(next);
}, RSVP.resolve()).then(function() {
    //all executed
});

Or values:

var idsToDelete = [1,2,3];

idsToDelete.reduce(function(cur, next) {
    return cur.then(function() {
        return http.post("/delete.php?id=" + next);
    });
}, RSVP.resolve()).then(function() {
    //all executed
});