opticon opticon - 1 month ago 11
AngularJS Question

$q.all - resolving too early?

I have a function that makes some server calls:

function doCalls(options) {
var deferred = $q.defer;
myService.doCallOne(options).then(function(response){
myService.doCallTwo().then(function() {
deferred.resolve();
});
});
return deferred.promise;
}


I have an array of different options and I want to create an array of promises to pass to
$q.all
, so I do this:

var promiseArray = [];
_.each(optionArray, function(options) {
promiseArray.push(doCalls(options));
});


Then I try to wait for them to resolve:

$q.all(promiseArray).then(function() {
doNextPart();
});


Problem is,
doNextPart()
seems to be getting called before any of my promises resolve. Am I doing anything obviously wrong here?

Answer

You forgot to call $q.defer, so that it didn't actually create a deferred. Your doCalls function calls returned undefined, your deferred.resolve() calls threw exceptions (that were swallowed by the promises), and $q.all immediately fulfilled with an array of undefineds.

You could change your code to

var deferred = $q.defer();
//                     ^^

but really you should avoid the deferred antipattern! Just use

function doCalls(options) {
    return myService.doCallOne(options).then(function(response){
        return myService.doCallTwo();
    }).then(function(secondResponse) {
        return undefined; // you might want to omit this
    });
}
Comments