我正在使用 Next.js/React.js。我正在使用 this API得到一个特定的国家。
例如,此响应中有一个称为边框的数组。
borders: [
"CAN",
"MEX",
],
例如,有一个基于边界获取数据的端点。https://restcountries.eu/rest/v2/alpha/can
如何获取两个边界的数据,即边界数组中的每个元素?这是我试图在一个循环中进行的两个 API 调用,但我没有定义。
export async function getServerSideProps(context) {
const { name } = context.params;
const res = await fetch(`https://restcountries.eu/rest/v2/name/${name}?fullText=true`)
const countryRes = await res.json();
const country = countryRes[0];
// Get the borders
const borders = country.borders;
// I'm making an API call to each element in array
const borderCountr = borders.forEach(border => {
fetch(`https://restcountries.eu/rest/v2/alpha/${border}`);
});
console.log(borderCountr); // undefinded
if (!country) {
return {
notFound: true,
}
}
return {
props: { country }
}
}
最佳答案
一个好的方法是使用 Promise.all
,以确保每次提取都正确执行。此外,您需要使这些调用异步。就像是:
const borderCountr = await Promise.all(
borders.map(async (border) => {
const response = await fetch(`https://restcountries.eu/rest/v2/alpha/${border}`);
return await response.json();
})
);
console.log(borderCountr[0], borderCountr[1]);
关于javascript - 如何对数组中的每个元素进行 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66505445/