簡體   English   中英

如何使 API 調用數組中的每個元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM