2016-05-13 124 views
6

我正在使用the axios承诺库,但我的问题适用于我认为更一般的情况。现在,我正在循环一些数据,并在每次迭代中创建一个REST调用。
随着每个调用完成,我需要将返回值添加到对象。在高层次上,它看起来像这样:等待在循环中调用的所有承诺完成

var mainObject = {}; 

myArrayOfData.forEach(function(singleElement){ 
    myUrl = singleElement.webAddress; 
    axios.get(myUrl) 
    .then(function(response) { 
    mainObject[response.identifier] = response.value; 
    }); 
}); 

console.log(convertToStringValue(mainObject)); 

发生了什么事,当然当我打电话console.logmainObject不具有任何数据还,因为爱可信还是伸手是。处理这种情况的好方法是什么?

Axios确实有一个all方法以及一个姊妹spread其中一个,但它们似乎是有用的,如果你提前知道你会打多少个电话,而在我的情况下,我不知道有多少循环迭代将会出现。

回答

22

你需要收集所有的承诺数组,然后使用axios.all

var mainObject = {}, 
    promises = []; 

myArrayOfData.forEach(function(singleElement){ 
    myUrl = singleElement.webAddress; 
    promises.push(axios.get(myUrl)) 
}); 

axios.all(promises).then(function(results) { 
    results.forEach(function(response) { 
     mainObject[response.identifier] = response.value; 
    }) 
}); 

console.log(convertToStringValue(mainObject)); 

它在axios docs

定律描述