opticon opticon - 1 year ago 59
Javascript Question

Serialize calls in $q.all

Requirements have changed and I'm in a position where I can either completely refactor a boatload of code, or figure out how to serialize a number of functions in a


var serverCalls = [];

_.each(items, function(item) {

return $q.all(serverCalls);

I'm wondering if there is a way to call the functions in
in sequence instead of in parallel without having to massively refactor the code that puts it all together.

Answer Source

If you are needing to run them in sequence, you need to make sure that you stack up an array of all of the results so that the outside world still gets the array of results that would normally have been returned from $q.all:

var serverCalls = Promise.resolve();
var results = [];

_.each(items, function(item) {
    // remember, .then() returns a new promise
    serverCalls = serverCalls.then(function (result) {
        return processItem(item);

return serverCalls.then(function () {
    return results;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download