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

4
我使用 Next.js / React.js。我正在使用此 API 获取特定国家:链接
响应中有一个名为 borders 的数组,例如。
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 }
  }
}

Array.forEach doesn't return anything. You need const borderCountr = await Promise.all(borders.map => fetch(...).then(r => r.json())); - user5734311
2个回答

6
一个好的方法是使用Promise.all来确保每个fetch都被正确执行。此外,你需要将这些调用变成异步的。可以使用以下方式:
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]);

0
// 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返回未定义,因此这是您的变量内容。


当我在fetch前面添加await时,出现以下错误 - 语法错误:'await'仅允许在异步函数内部和模块的顶层使用。 - user15342453
第一,fetch不是在异步函数中编写的,因此无法在那里编写await。如果您将async添加到箭头函数中,则可以编写await。 - Seti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接