使用 Promise.all 在多个 URL 上调用 fetch()
Calling fetch() on multiple URLs using Promise.all
我正试图在多个 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])
我是不是在做傻事?
第 4 行缺少 return
:
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)
}
}
我正试图在多个 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])
我是不是在做傻事?
return
:
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)
}
}