将axios请求的响应推入数组

我一直在努力解决这个问题,需要解决方案的帮助。我在JSON中有一个ID数组,并且正在对该数组进行迭代并针对每个ID进行GET请求。然后,我想将这些GET请求的响应推送到数组中。


这是我用来将注册信息推送到数组中的函数。它通过一组ID进行迭代:


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;

};

这是我调用该代码的地方:


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”显示为“ [{...}]”。


我知道这是一个与Promise相关的问题(我在实际执行之前要返回注册数组),但是我不知道如何解决它!一些友好的帮助将不胜感激!


HUH函数
浏览 237回答 3
3回答

四季花海

由于getRegistrations(event)返回的是诺言,因此您应该对中的返回值执行操作then。代替let registrations = this.getRegistrations(event);console.log(registrations);做这个this.getRegistrations(event).then(registrations => {&nbsp; console.log(registrations);&nbsp; // other operations on registrations});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript