将 axios 请求的响应推送到数组中 [英] Pushing responses of axios request into array

查看:29
本文介绍了将 axios 请求的响应推送到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决这个问题,需要解决方案的帮助.我在 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 控制台中,注册"显示为[]",而注册 2"显示为[{...}]".

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 相关的问题(我在实际推送之前返回了注册数组)但我不知道如何解决它!非常感谢一些友好的帮助!

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,因此它会返回 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆