等待所有承诺在循环中完成

jkj*_*000 16 javascript promise axios

我正在使用axios promise库,但我认为我的问题更为普遍.现在我循环遍历一些数据并在每次迭代时进行一次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));
Run Code Online (Sandbox Code Playgroud)

当然发生了什么事情,当我打电话console.logmainObject它时还没有任何数据,因为axios仍在伸出手.处理这种情况的好方法是什么?

Axios确实有一个all方法和一个姐妹方法spread,但如果你提前知道你将要拨多少个电话,它们似乎是有用的,而在我的情况下,我不知道会有多少循环迭代.

kra*_*asu 48

您需要在数组中收集所有承诺,然后使用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));
Run Code Online (Sandbox Code Playgroud)

它在axios docs有所描述