Angular $q.all method

So I have recently been working back within angular. It is like drinking wine with an old friend, you do not forget the good times and toast to the success.

I often enjoy using the $q library that comes with angular. (always check out the documentation on the angular site).

Well this time round I finally found myself in the need for running multiple $http calls with promises that I then needed to resolve when both had resolved in my code.

Originally I had gone down with this bizarre asynchronous synchronous route:

$q.when(true).then(function(ready){
    var anotherDeferred = $q.defer();
    anotherDeferred.resolve(myController.sendMessage(message, person, true));
    return anotherDeferred.promise;
}).then(function(ready){
    myController.updateMeta(data).then(function(success){
        myController.returnedText      = '';
        myController.showReturnedPopup = false;
    });
});

NB: In case you wonder I have my controllers with no $scope I do this at top of my controllers:

var myController = this;

So if you see myController, in your code you can easily pull in $scope in your dependencies and use that instead of myController

One other note, if using a dependency, remember to include it in your code for access:

myApp.controller("myController",function($q){
    //$q is available here
    var myController = this;
});

Anyway back to the code. The mistake is that I do not need each call to to resolve for the next one to happen. So in this instance it makes a lot more sense to be able to run two $http requests at the same time. Wait for them both to resolve then carry on.

So I found solice in $q.all which neatened it up to this:

var promise1 = myController.sendMessage(message, person, true);
var promise2 = myController.updateMeta(data);

$q.all([promise1, promise2]).then(function(data){
    console.log(data[0], data[1]);
});

To show it with $http:

var promise1 = $http({method: 'POST', url: '/url-one'});
var promise2 = $http({method: 'DELETE', url: '/url-two'});
var promise3 = $http({method: 'GET', url: '/url-two'});

$q.all([promise1, promise2, promise3]).then(function(data){
    console.log(data[0], data[1], data[2]);
},function(error){
    console.log(error);
});

As you can see we get a property returned that has an array of the outcome of our promises.

Beware a failure

But as nice as this is and handy, it does come with a flaw (not a major flaw and makes sense really).

If one promise fails, they all fail

This means you would no matter what end up in your fail method, so be aware of what you do with $q.all




Random Posts

  • No, It is not
    No it is not Stop clicking those enticing links! (this …