【问题标题】:AngularJS : multiple promise wait allAngularJS:多个承诺等待所有
【发布时间】:2014-06-14 03:10:32
【问题描述】:

我有一个关于多重承诺的小问题。 我怎么能等待所有的承诺都将完成以返回最终结果。

查看我的代码:

getInfo : function(){
        return promiseA.then(function(result){
               info  = result;
               //this function have also promises 
               return ServiceA.functionA(info.login)
                      .then(function(favouriteItems){
                          info.favorites = favouriteItems;
                          return $q.when(info);
                       });      
         });       
},

我的目标是在返回值之前等待 ServiceA.functionA 的结果。

谢谢

K.L

【问题讨论】:

  • 使用$q.all()
  • 在这种情况下不可能使用$q.all(),因为函数ServiceA.functionA需要使用promiseA的结果。
  • 在我看来你已经是了。 getInfo 返回的 Promise 将在其 favorites 项目在最终回调中修改后使用 info 解析。

标签: angularjs promise


【解决方案1】:

你需要使用$q.all()

这是一个关于这个问题的好帖子:stackoverflow.com/questions/21310964/angularjs-q-all

【讨论】:

    【解决方案2】:
    getInfo : function() {
      return promiseA.then(function(result){           
        return ServiceA.functionA(result.login).then(function(favouriteItems){
          result.favorites = favouriteItems;
          return result;
        });      
      });       
    },
    

    这样使用:

    api.getInfo().then(function(result){
      // use result and result.favorites
    }, function(err){
      // here you can be if an error occurred in promiseA or in ServiceA.functionA
    })
    

    【讨论】:

    • 我们总是鼓励至少对你的代码在做什么做一点解释。
    【解决方案3】:

    我写了另一个问题的答案,说明了使用 $q.all 方法解决此问题的方法。

    查看:AngularJS: Listen to events, one after the other

    【讨论】:

      【解决方案4】:
      function getInfo() {
        var deferred = $q.defer();
      
        promiseA.then(function(result){
          info  = result;
          // this function have also promises 
          ServiceA.functionA(info.login)
            .then(function(favouriteItems){
               info.favorites = favouriteItems;
                 // the magic
                 deferred.resolve(info);
                 // at this point, you can resolve any value
            });      
          });
        }
      
        return deferred.promise;
      }
      

      然后你可以调用该函数并得到一个承诺......

      var promise = getInfo();
      promise.then(successCallback, errorCallback, notifyCallback);
      

      successCallback 只会在 resolve 被延迟对象调用后被调用。

      【讨论】:

      • 您在其他请求的错误回调中手动使用$q.reject(reason) 调用它。
      猜你喜欢
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2014-03-12
      • 2020-03-26
      • 1970-01-01
      • 2020-04-22
      相关资源
      最近更新 更多