[使用Promise.all在多个URL上调用fetch()

问题描述 投票:0回答:1

我正在尝试在多个URL上获取JSON数据。 URL是一个固定的字符串,在其末尾连接了唯一的键。这些键作为数组提供,我正在使用map()进行迭代。结果数据传递到Promise.all(),但返回未定义。我无法为自己的生命找出原因吗?

export const fetchApiEvents = async eventIds => {
    try {
        const events = await Promise.all(eventIds.map(id => {
            fetch('http://api_url/events/' + id)
                .then(res => res.json())
        }))
        return events
    } catch (e) {
        console.log('An error occured fetching the events: ', e)
    }
}

然后我将此函数称为效果:

    useEffect(() => {
        fetchApiEvents(eventIds)
            .then(response => setEvents(response))
    }, [eventIds])

我做的事真的很愚蠢吗?

javascript reactjs es6-promise
1个回答
0
投票

return在第4行中丢失:

export const fetchApiEvents = async eventIds => {
    try {
        const events = await Promise.all(eventIds.map(id => {
            return fetch('http://api_url/events/' + id)
                .then(res => res.json())
        }))
        return events
    } catch (e) {
        console.log('An error occured fetching the events: ', e)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.