如何为数组中的每个元素进行 API 调用

4 javascript rest reactjs next.js

我正在使用 Next.js / React.js。我正在使用此 API来获取特定国家/地区。

例如,此响应中有一个名为 borders 的数组。

borders: [
   "CAN",
   "MEX",
],
Run Code Online (Sandbox Code Playgroud)

例如,有一个端点可以根据边界获取数据。

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 }
  }
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*lid 6

一个好的方法是使用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]);
Run Code Online (Sandbox Code Playgroud)