问题描述
我正在使用 axios 承诺库,但我认为我的问题更适用.现在我正在遍历一些数据并在每次迭代中进行一次 REST 调用.
当每次调用完成时,我需要将返回值添加到一个对象中.在高层次上,它看起来像这样:
I'm using the axios promise library, but my question applies more generally I think. Right now I'm looping over some data and making a single REST call per iteration.
As each call completes I need to add the return value to an object. At a high level, it looks like this:
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 仍在伸出援手.处理这种情况的好方法是什么?
What's happening of course is when I call console.log
the mainObject
doesn't have any data in it yet, since axios is still reaching out. What's a good way of dealing with this situation?
Axios 确实有一个 all
方法以及一个姊妹 spread
方法,但是如果您提前知道将要进行多少次调用,它们似乎很有用制作,而在我的情况下,我不知道会有多少循环迭代.
Axios does have an all
method along with a sister spread
one, but they appear to be of use if you know ahead of time how many calls you'll be making, whereas in my case I don't know how many loop iterations there will be.
推荐答案
你需要将所有的 promise 收集到一个数组中,然后使用 Promise.all
:
You need to collect all of your promises in an array and then use 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, ' ');
}
// 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 文档(执行多个并发请求)中有描述部分).
It's described in axios docs (Performing multiple concurrent requests section).
在 2020 年 5 月之前,可以使用 axios.all(),现已弃用.
Before May 2020 it was possible to do with axios.all(), which is now deprecated.
这篇关于等待循环中调用的所有承诺完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!