javascript - 链接通过 for 循环创建的多个 Promise

标签 javascript angularjs

我一直在通过 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; 

  });

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

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

最佳答案

您应该使用$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);

  });

来自文档:

all(promises);

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

Parameters

An array or hash of promises.

Returns

Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.

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

关于javascript - 链接通过 for 循环创建的多个 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555228/

相关文章:

javascript - 使用 Jquery 的 AJAX 无法跨 JSP 页面工作

javascript - Jquery .html() 不工作 - 选择 html

angularjs - 使用带有智能表格 Angular 的固定标题使表格 100%

python - 带有 Angular 的 flask : POST form is empty

JavaScript 垃圾邮件过滤器

javascript - 等待元素出现或返回 false

javascript - 如何循环数组生成js代码?

javascript - 仅在 MEAN js 中对经过身份验证的用户授予页面查看权限

angularjs - 将简单的Dart代码转换为TypeScript

angularjs - Jasmine 测试没有看到 AngularJS 模块