1

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?

opticon
  • 3,494
  • 5
  • 37
  • 61

1 Answers1

3

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
    });
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • D'oh. Yep. That did it. Now that she works I'll rip out that antipattern! – opticon Oct 25 '16 at 18:08
  • Not sure if this is the place for a follow-up, but how do I handle possible server errors in the calls? Ie. How do I reject a promise using that preferred pattern? – opticon Oct 25 '16 at 18:18
  • You can `throw` inside `then` callbacks (the exception will be caught and the promise will be rejected with it), or you can `return` a rejected promise from the `then` callback (`$q.reject(new Error(…))`). – Bergi Oct 25 '16 at 18:35