javascript - 如何使用 array.map 方法获取数组中每个元素的数据
问题描述
我想为数组中的每个对象获取数据并返回一个包含先前和新获取的数据的新对象数组。我被困在获取结果数组上,因为我的函数正在返回一个已解决的未定义承诺数组。我正在使用一个航班搜索 api,它使用apca函数来获取
export const searchApcaLocation = async (dataArr,setDeals) => {
const promises = await dataArr.map(async item => {
apca.request(item.destination);
apca.onSuccess = (data) => {
return fetch('http://localhost:3050/googlePlaceSearch',{
method:"post",
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
cityName:data.airports[0].city
})
})
.then(res => res.json())
.then(imagelinkData => {
const locationObject = {
data: item,
imagelink: imagelinkData.link
}
return locationObject
})
.catch(err => console.log('error on image search',err))
};
apca.onError = (data) => {
console.log('error',data)
};
})
const results = await Promise.all(promises)
return results
}
有人可以指导我我做错了什么吗?
编辑:当我试图修复它时,我意识到问题是我没有在我的 map 函数中返回任何东西,但是如果试图返回 apca.onSuccess 我得到一个函数数组
解决方案
您的问题可能是,您正在使用 async/await 然后一起阻塞。让我总结一下正在发生的事情:
1)你等待 dataArray.map
2)在地图回调中,您使用apca的onSuccess方法
3)在此方法中,您正在使用 then 块,这些块在您得到响应之前不会等待。
此时您返回 locationObject,您的函数已经到达 return 语句并尝试返回结果。但是结果当然是不确定的,因为它们根本没有得到解决。
另外,请记住,您的函数返回另一个承诺,因为您使用了 async/await,您必须解决导入它的位置。
干杯:)