[英]How to make API calls for each element in array
我正在使用 Next.js / React.js。 我正在使用此 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]);
// I'm making an API call to each element in array
const borderCountr = borders.forEach(border => {
fetch(`https://restcountries.eu/rest/v2/alpha/${border}`);
});
这不是等待(您不需要等待任何获取结果),代码在此处执行,并且无需等待获取完成 - 执行下一行。 由于 forEach 返回未定义,那是您的变量内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.