opticon opticon - 9 months ago 66
AngularJS Question

$q.all - resolving too early?

I have a function that makes some server calls:

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

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

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

Then I try to wait for them to resolve:

$q.all(promiseArray).then(function() {

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

Answer Source

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