问题描述
我正在编写一个函数,该函数应该带有一个动物id的对象,并基于该对象中的键向api请求并获取与该键值相关的数据(例如id)。
问题是,当我尝试将获取的猫狗推到数组中时,无法在Object.keys()。foreEach循环之外显示对象。
我如何在我的动物数组中返回获取的数据?
const animalIds = {
dogId: "11111",catId: "22222",};
const findData = async (animalIds) => {
let animals = [];
Object.keys(animalIds).forEach(async (key) => {
const id = relatedTo[key];
if (key === 'dogId') {
const dog = await api.getDog(id);
animals.push(dog)
}
if (key === 'catId') {
const cat = await api.getCat(id);
animals.push(cat)
}
});
// console.log(animals) is an empty []
return animals
}
调用函数时,我正在使用await findData(animalIds)。
解决方法
问题在于.forEach(async (key) => {
不等待功能完成,而只是启动它们。您需要的是带有map
的{{1}},如下所示:
await Promise.all()
这会立即启动所有功能(与forEach相同),然后等待所有功能完成后再继续。这样await Promise.all(Object.keys(animalIds).map(async (key) => {
const id = relatedTo[key];
if (key === 'dogId') {
const dog = await api.getDog(id);
animals.push(dog)
}
if (key === 'catId') {
const cat = await api.getCat(id);
animals.push(cat)
}
}));
数组将包含结果。