28

我正在使用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));

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

Axios 确实有一个all方法和一个姊妹方法spread,但是如果您提前知道要进行多少次调用,它们似乎很有用,而在我的情况下,我不知道会有多少循环迭代。

4

1 回答 1

65

您需要将所有承诺收集在一个数组中,然后使用Promise.all

// Example of gathering latest Stack Exchange questions across multiple sites
// Helpers for example
const apiUrl = 'https://api.stackexchange.com/2.2/questions?pagesize=1&order=desc&sort=activity&site=',
    sites = ['stackoverflow', 'ubuntu', 'superuser'],
    myArrayOfData = sites.map(function (site) {
        return {webAddress: apiUrl + site};
    });

function convertToStringValue(obj) {
    return JSON.stringify(obj, null, '\t');
}

// Original question code
let mainObject = {},
    promises = [];

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

Promise.all(promises).then(function (results) {
    results.forEach(function (response) {
        const question = response.data.items[0];
        mainObject[question.question_id] = {
            title: question.title,
            link: question.link
        };
    });

    console.log(convertToStringValue(mainObject));
});
<script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script>

它在axios 文档(执行多个并发请求部分)中进行了描述。

在 2020 年 5 月之前,可以使用 axios.all(),现在已弃用

于 2016-05-13T15:27:48.797 回答