在我将秘密更改为真正的密钥时,api调用很好。
我明白这个错误,但不确定我是否能解决这个问题。
这里是我想要达到的目标的一个例子。我得到了所有的狗品种通过API调用。这很好,等待之后数组就会出现。现在我要做的是循环所有的狗品种,并从另一个API获得有关国家的信息。比它告诉我
等待仅在异步函数和模块的顶层主体中有效。
我不能把它放在最上面,因为我依赖的是另一个结果。如何才能做到这一点?
const axios = require('axios').default;
async function getCountry(breed){
const countryOptions = {
method: 'GET',
url: 'https://countries-cities.p.rapidapi.com/location/country/'+breed.origin,
headers: {
'X-RapidAPI-Key': 'SECRET',
'X-RapidAPI-Host': 'countries-cities.p.rapidapi.com'
}
};
await axios.get("https://countries-cities.p.rapidapi.com/location/country/'+breed.origin",countryOptions);
}
async function GetDogs(){
try{
const options = {
method: 'GET',
url: 'https://dog-breeds2.p.rapidapi.com/dog_breeds',
params: {limit: '2'},
headers:{'X-RapidAPI-Key': 'SECRET',
'X-RapidAPI-Host': 'dog-breeds2.p.rapidapi.com'}
};
const dogBreeds = await axios.get("https://dog-breeds2.p.rapidapi.com/dog_breeds",options);
dogBreeds.data.forEach((breed)=>{
const country = await getCountry(breed);
console.log(country);
})
}
catch(err){
console.log(err);
}
};
GetDogs();
发布于 2022-08-25 21:06:10
可以将async
函数作为回调传递给forEach
方法。
dogBreeds.data.forEach(async (breed)=>{
const country = await getCountry(breed);
console.log(country);
});
正如注释中提到的,您可以使用for...of
循环来保持当前函数块的相同async
作用域。
for (const breed of dogBreeds.data) {
const country = await getCountry(breed);
console.log(country);
}
但是您可能想要对getCountry
的结果做些什么。
getCountry
不返回任何东西,需要注意。
因此,已解决的Promise
undefined
**.**将产生。
如果您修复了这个问题,那么在map
数组上使用dogBreeds.data
方法与Promise.all
并行进行查询可能会更有用。其结果将是一系列国家。
const countries = await Promise.all(dogBreeds.data.map((breed) => getCountry(breed)));
https://stackoverflow.com/questions/73493630
复制相似问题