jaaksarv jaaksarv -4 years ago 181
Javascript Question

How can I execute array of promises in sequential order?

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:


But, how can I run them in sequence?

I can manually stack them like this


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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download