Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未接收API调用的html呈现_Javascript_Api_Async Await - Fatal编程技术网

Javascript 未接收API调用的html呈现

Javascript 未接收API调用的html呈现,javascript,api,async-await,Javascript,Api,Async Await,我试图练习向第三方api发出请求,但我无法将响应呈现为html,但当我控制台记录它时,我得到了一个奇怪的响应。请参阅下面的代码 script.js async function getCountries(){ let url = 'https://restcountries.eu/rest/v2/lang/es' try{ let res = await fetch(url); return await res.json() }catch(error){ co

我试图练习向第三方api发出请求,但我无法将响应呈现为html,但当我控制台记录它时,我得到了一个奇怪的响应。请参阅下面的代码

script.js

async function getCountries(){
  let url = 'https://restcountries.eu/rest/v2/lang/es'
  try{
    let res = await fetch(url);
    return await res.json()
  }catch(error){
    console.log(error)
  }
}

async function renderCountries(){
  let countries = getCountries();
  console.log(countries)
  let html = '';
  countries.forEach(country =>{
    let htmlSeg = `
    <div class="user">
      <h2>${country.name}</h2>
      <p>${country.capital}</p>
      <p>${country.region}</p>
      <p>${country.subregion}</p>
    </div>`;

    html += htmlSeg;

    
})

let container = document.querySelector('#spot')
container.innerHTML = html

}

renderCountries()
下面是我在控制台登录时得到的响应示例

0: {name: "Argentina", topLevelDomain: Array(1), alpha2Code: "AR", alpha3Code: "ARG", callingCodes: Array(1), …}
1: {name: "Belize", topLevelDomain: Array(1), alpha2Code: "BZ", alpha3Code: "BLZ", callingCodes: Array(1), …}
2: {name: "Bolivia (Plurinational State of)", topLevelDomain: Array(1), alpha2Code: "BO", alpha3Code: "BOL", callingCodes: Array(1), …}
3: {name: "Chile", topLevelDomain: Array(1), alpha2Code: "CL", alpha3Code: "CHL", calli

请让我知道我在这里做错了什么

您需要添加
等待

let countries = await getCountries();

谢谢你,先生,这就清楚了。
0: {name: "Argentina", topLevelDomain: Array(1), alpha2Code: "AR", alpha3Code: "ARG", callingCodes: Array(1), …}
1: {name: "Belize", topLevelDomain: Array(1), alpha2Code: "BZ", alpha3Code: "BLZ", callingCodes: Array(1), …}
2: {name: "Bolivia (Plurinational State of)", topLevelDomain: Array(1), alpha2Code: "BO", alpha3Code: "BOL", callingCodes: Array(1), …}
3: {name: "Chile", topLevelDomain: Array(1), alpha2Code: "CL", alpha3Code: "CHL", calli
let countries = await getCountries();