How to resolve $q.all?

10,714

$q.all creates a promise that is automatically resolved when all of the promises you pass it are resolved or rejected when any of the promises are rejected.

If you pass it an array like you do then the function to handle a successful resolution will receive an array with each item being the resolution for the promise of the same index, e.g.:

  var resolveTopics = function() {
    $q.all([getToken(), getUserId()])
    .then(function(resolutions){
      var token  = resolutions[0];
      var userId = resolutions[1];
    });
  }

I personally think it is more readable to pass all an object so that you get an object in your handler where the values are the resolutions for the corresponding promise, e.g.:

  var resolveTopics = function() {
    $q.all({token: getToken(), userId: getUserId()})
    .then(function(resolutions){
      var token  = resolutions.token;
      var userId = resolutions.userId;
    });
  }
Share:
10,714
gumenimeda
Author by

gumenimeda

“I would rather be ashes than dust! I would rather that my spark should burn out in a brilliant blaze than it should be stifled by dry-rot. I would rather be a superb meteor, every atom of me in magnificent glow, than a sleepy and permanent planet. The function of man is to live, not to exist. I shall not waste my days trying to prolong them. I shall use my time.” Jack London

Updated on July 21, 2022

Comments

  • gumenimeda
    gumenimeda almost 2 years

    I have 2 functions, both returning promises:

        var getToken = function() {
    
            var tokenDeferred = $q.defer();         
            socket.on('token', function(token) {
                tokenDeferred.resolve(token);
            });
            //return promise
            return tokenDeferred.promise;
        }
    
        var getUserId = function() {
            var userIdDeferred = $q.defer();
            userIdDeferred.resolve('someid');           
            return userIdDeferred.promise;
        }
    

    Now I have a list of topics that I would like to update as soon as these two promises get resolved

        var topics = {      
            firstTopic: 'myApp.firstTopic.',  
            secondTopic: 'myApp.secondTopic.',
            thirdTopic: 'myApp.thirdTopic.',
            fourthTopic: 'myApp.fourthTopic.',
        };
    

    Resolved topics should look like this myApp.firstTopic.someid.sometoken

    var resolveTopics = function() {
        $q.all([getToken(), getUserId()])
        .then(function(){
    
            //How can I resolve these topics in here?
    
        });
    }