簡體   English   中英

鏈接通過for循環創建的多個promise

[英]Chaining multiple promises created through for loop

我一直在通過這個鏈接研究諾言,我理解了它的想法

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; 

  });

但是,我的用例需要遍歷並發送創建多個1的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);

  });

從文檔中:

全部(應許);

在將所有輸入的Promise解析后,將多個Promise合並為一個Promise。

參量

承諾的數組或哈希。

退貨

返回將用值的數組/哈希值解析的單個promise,每個值對應於promise數組/哈希中相同索引/鍵處的promise。 如果任何一個承諾都被拒絕解決,則此結果承諾將以相同的拒絕值被拒絕。

-AngularJS $ q服務API參考-$ q.all

您可以利用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);
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM