问题描述
我正在使用 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.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, '\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文档中进行了描述(执行多个并发请求部分).
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.
这篇关于等待循环中调用的所有诺言完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!