opticon opticon - 14 days ago 5
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

$q.all
promise.

var serverCalls = [];

_.each(items, function(item) {
serverCalls.push(processItem(item));
});

return $q.all(serverCalls);


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

Answer

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) {
        results.push(result);
        return processItem(item);
    });
});

return serverCalls.then(function () {
    return results;
});
Comments