[英]How to make API calls for each element in array
I'm using Next.js / React.js.我正在使用 Next.js / React.js。 I'm using this API to get a specific country.
我正在使用此 API来获取特定国家/地区。
There's an array on this response called borders, for example.例如,此响应中有一个称为边框的数组。
borders: [
"CAN",
"MEX",
],
There's an end point to get the data based on a border, for example.例如,有一个基于边界获取数据的端点。
https://restcountries.eu/rest/v2/alpha/can https://restcountries.eu/rest/v2/alpha/can
How would I get the data both borders, ie each element in the borders array?我如何获得两个边界的数据,即边界数组中的每个元素? It's two API calls that I've tried to make in a loop, but I get undefined.
这是我试图在一个循环中进行的两个 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 }
}
}
A good approach would be using Promise.all
, to be sure that each fetch is correctly executed.一个好的方法是使用
Promise.all
,以确保正确执行每个提取。 Also, you need to make those calls async.此外,您需要使这些调用异步。 something like:
就像是:
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}`);
});
This is not awaited (you do not await for ANY of the fetch results) that mens, the code executes here, and without waiting for the fetches to finish - executed the next lines.这不是等待(您不需要等待任何获取结果),代码在此处执行,并且无需等待获取完成 - 执行下一行。 As forEach returns undefined, that is your variable content.
由于 forEach 返回未定义,那是您的变量内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.