【问题标题】:AngularJS: promise in a loopAngularJS:循环中的承诺
【发布时间】:2017-11-17 23:36:56
【问题描述】:

我无法执行承诺循环。

我拨打服务电话以获取提供商列表,然后对于每个提供商,我再拨打服务电话以获取客户。

供应商有 1 个或多个客户。所以最终的客户名单是要装饰和展示的。

我正在尝试实现的其他格式:

*serviceA.getProvider(){

  foreach(providers){

   foreach(provider.customerID){

    serviceB.getCustomer(customerId)

   }

  }

}
.then( 

  foreach(Customer){

   updateTheCustomer;

   addUpdatedCustomerToAList

  }

displayUpdatedCustomreList();

)*

我写了下面的代码,但不起作用

doTheJob(model: Object) {
    let A = [];
    let B = [];

let fetchP = function(obj) {
  obj.Service1.fetchAllP().then(function (response) {
    let P = cloneDeep(response.data);

    _.forEach(P, function(prov) {
      _.forEach(prov.CIds, function(Id) {
        A.push(Id);
      });
    });

    _.forEach(A, function(CId) {
      return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
                                        //So, clearly, returning promise inside loop isn't working
    });
  })
  .then(function(response) {
    B.push(response.data); //This response is undefined

    angular.forEach(B, function (value) {
      obj.updateAdr(value)
    });

    obj.dispay(B);
  });
};
fetchP(this);


}

【问题讨论】:

    标签: angularjs loops user-interface promise q


    【解决方案1】:

    forEach 在其中使用 return 时不要停止,尝试使用普通循环代替,为什么不直接使用 for 循环?

    【讨论】:

      【解决方案2】:
      _.forEach(A, function(CId) {
         return obj.Service2.getById(CId);
      }
      

      如@Ze Rubeus 所述,如果您在 for 循环内的回调中返回该值将丢失,因为它不会返回给调用者。

      可能你想要这样的东西

      return Promise.all(A.map(function(CId){
         //collect each promise inside an array that will then be resolved
         return obj.Service2.getById(CId);
      })
      

      【讨论】:

      • 卡里姆,你是明星!您的解决方案绝对令人惊叹!谢谢
      • 很高兴它有帮助 ;)
      猜你喜欢
      • 1970-01-01
      • 2014-11-25
      • 2018-03-25
      • 1970-01-01
      • 2021-12-15
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多