将axios请求的响应推入数组 [英] Pushing responses of axios request into array
问题描述
我一直在努力解决这个问题,需要解决方案的帮助.我在JSON中有一个ID数组,并且正在对该数组进行迭代并针对每个ID进行GET请求.然后,我想将这些GET请求的响应推送到一个数组中.
I have been pounding my head against this problem, and need help with a solution. I have an array of IDs within a JSON, and I am iterating over that array and making a GET request of each ID. I want to then push the response of those GET requests into an array.
这是我用来将注册推入数组的功能.它正在遍历一组ID:
Here is the function I am using to push the registrations into the array. It is iterating through an array of IDs:
getRegistrations = async (event) => {
let registrations = [];
await event.registrations.forEach(registration => axios.get('/event/getRegistration', {
params: {
id: registration
}
}).then(res => {
registrations.push(res.data.properties)
}
).catch(err => console.log(err)));
return registrations;
};
在这里我要调用该代码:
Here is where I am calling that code:
render() {
let event = this.getEvent();
let registrations2 = [{
age: 19,
bio: 'test',
firstName: 'hello',
lastName: 'bye',
password: 'adadas',
telephone: "4920210213"
}];
if (this.props.listOfEvents.events.length !== 0 && !this.props.listOfEvents.gettingList && event) { //check if the array is empty and list has not been rendered yet
let columns = [];
let registrations = this.getRegistrations(event);
console.log(registrations);
let eventProperties = event.properties[0];
Object.keys(eventProperties).forEach(key => columns.push({
title: eventProperties[key].title,
dataIndex: key,
key: key
}));
console.log(registrations);
console.log(registrations2);
return (
<h1>hi</h1>
)
}
return <Loading/>
}
当我在控制台上登录"registrations"和"registrations2"时,它们应该非常相同.但是,在Google Chrome浏览器的javascript控制台中,注册"显示为"[]",其中"registrations2"显示为"[{......]]".
When I console-log 'registrations' vs 'registrations2' they should be very identical. However, in the javascript console on Google Chrome, 'registrations appears as '[]' where 'registrations2' appears as '[{...}]'.
我知道这是一个与Promise相关的问题(我在实际执行之前返回了registrations数组),但是我不知道如何解决它!一些友好的帮助将不胜感激!
I know that it is an issue related to promises (I am returning the registrations array before actually pushing) but I have no idea how to fix it! Some friendly help would be very much appreciated!
推荐答案
我建议Promise.all
,它将在所有承诺均已解决后解决单个Promise.从技术上讲,异步函数也是promise,因此它将返回promise.
I recommend Promise.all
, it will resolve single Promise after all promises have resolved. And technically async function is also promise so it will return promise.
这里是示例.
https://codesandbox.io/s/jzz1ko5l73?fontsize=14
这篇关于将axios请求的响应推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!