How to resolve $q.all?

后端 未结 1 707
执笔经年
执笔经年 2021-01-12 02:33

I have 2 functions, both returning promises:

    var getToken = function() {

        var tokenDeferred = $q.defer();         
        socket.on(\'token\', f         


        
相关标签:
1条回答
  • 2021-01-12 03:21

    $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;
        });
      }
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题