【问题标题】:Waiting for all promises called in a loop to finish等待循环中调用的所有承诺完成
【发布时间】:2016-09-09 20:58:21
【问题描述】:

我正在使用the 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.log 时,mainObject 中还没有任何数据,因为 axios 仍在伸出援手。处理这种情况的好方法是什么?

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

【问题讨论】:

    标签: javascript promise axios


    【解决方案1】:

    你需要将所有的 Promise 收集到一个数组中,然后使用 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 docs(执行多个并发请求部分)中有描述。

    在 2020 年 5 月之前,可以使用 axios.all(),which is now deprecated

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多