Question

I have an array of async functions, where it only makes sense to run one if the previous one has been resolved. You can think of them as HTT get requests to different URL, e.g.

$http.get('/step1')
$http.get('/step2')
$http.get('/step3')
$http.get('/step4')

How can I serialize them?

EDIT: There are N of them in an array. So I can't explicitly unroll them and join them with 'then', e.g.:

var calls = Array()

for(var i = 0; i < N; i++)
{
    var d = $q.defer();

    ...

    calls.push(d.promise);
}

..

// How to do resolve the elements of 'calls' in order?

EDIT 2:

I would like:

Running Step #0 
Step completed: #0 OK 
Running Step #1 
Step completed: #1 OK 
Running Step #2 
Step completed: #2 OK 
Running Step #3 
Step completed: #3 OK 
Running Step #4 
Step completed: #4 OK 
Running Step #5 
Step completed: #5 OK 

Not

Running Step #0 
Running Step #1 
Running Step #2 
Running Step #3 
Running Step #4 
Running Step #5 
Step completed: #0 OK 
Step completed: #1 OK 
Step completed: #2 OK 
Step completed: #3 OK 
Step completed: #4 OK 
Step completed: #5 OK 
Was it helpful?

Solution

Using lodash for brevity.

_.reduce(_.rest(calls), function(promise, call) {
  return promise.then(function() {
    return call();
  });
}, _.first(calls)()).then(function() {
  // do something after they are all done sequentially.
});

OTHER TIPS

var cur = $q.when();
var promises = [$http.get('/step1'), $http.get('/step2'), ...];

promises.forEach(function(promise){
    cur = cur.then(function(){
        return promise;
    });
})

cur.then(function(){
    //All done
})

Your array needs to be of the data you want to use, and the function call done after the previous promise has resolved. You could adapt @Esailija's solution by putting the call inside the cur.then function, however the idiomatic way to do this is with [].reduce:

var urls = ["/step1", "/step2", "step3"];

var done = urls.reduce(function (previous, url) {
    return previous.then(function () {
        return $http.get(url);
    });
}, $q.when());

done.then( ... );

See Kris Kowal's Qooqbooq

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top