【问题标题】:Chaining multiple promises created through for loop链接通过 for 循环创建的多个 Promise
【发布时间】:2016-11-28 01:21:11
【问题描述】:

我一直在通过this link研究promise,我理解它的想法

var parentID;

$http.get('/api/user/name')
  .then(function(response) {

  parentID = response.data['ID'];
  for (var i = 0; i < response.data['event-types'].length; i++) {
    return $http.get('/api/security/' + response.data['event-types'][i]['key']);
  }

  })
  .then(function(response) {

    // response only returns one result of the many promises from the for loop
    // do something with parentID; 

  });

但是,我的用例需要循环并发送创建多个承诺。我试图链接上面的示例,但只执行了从 for 循环创建的唯一一个承诺。

如何在继续访问变量 parentID 的同时继续链接所有承诺?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

您应该使用 $q.all,因为它与 AngularJS 摘要循环集成在一起。

var parentID;

$http.get('/api/user/name')
  .then(function(response) {

      parentID = response.data['ID'];
      var promiseList = [];
      for (var i = 0; i < response.data['event-types'].length; i++) {
          var iPromise = $http.get('/api/security/' + response.data['event-types'][i]['key']);
          promiseList.push(iPromise);
      };
      return $q.all(promiseList);

  })
  .then(function(responseList) {

       console.log(responseList);

  });

来自文档:

所有(承诺);

将多个 Promise 组合成一个 Promise,当所有输入 Promise 都已解析时,该 Promise 将被解析。

参数

promise 的数组或散列。

退货

返回一个单一的promise,它将用一个数组/哈希值解析,每个值对应于promise数组/哈希中相同索引/键的promise。如果任何一个 Promise 以一个拒绝的方式解决,这个产生的 Promise 将以相同的拒绝值被拒绝。

--AngularJS $q Service API Reference -- $q.all

【讨论】:

    【解决方案2】:

    您可以使用Promise.all(),将Array.prototype.map() 替换为for 循环

      var parentID;
    
      $http.get('/api/user/name')
      .then(function(response) {    
      parentID = response.data['ID'];
      return Promise.all(response.data['event-types'].map(function(_, i) {
        return $http.get('/api/security/' + response.data['event-types'][i]['key'])
        })) 
      })
      .then(function(response) {
    
        // response only returns one result of the many promises from the for loop
        // do something with parentID; 
    
      })
      .catch(function(err) {
        console.log(err);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      相关资源
      最近更新 更多