从 Fetch 访问响应数据

Accessing response data from Fetch

这是我的获取函数:

getAllCountries = async () => {
    try {
      const response = await fetch("https://restcountries.eu/rest/v2/all");
      const result = response.json();
      console.log(result);
      this.countriesList = result;
    } catch (error) {
      console.log(error);
    }
  };

在控制台中,它记录

为什么那里登录了两个承诺,我如何访问 PromiseResult。 我尝试了 console.log(result[0]) 但没有成功

json() returns一个承诺,所以:

  getAllCountries = async () => {
    try {
      const response = await fetch("https://restcountries.eu/rest/v2/all");
      const result = await response.json();
//                   ^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− add
      console.log(result);
      this.countriesList = result;
    } catch (error) {
      console.log(error);
    }
  };

旁注:该代码正在成为 fetch API footgun 的牺牲品:fetch 仅在 network 错误上拒绝其承诺,不是 HTTP 错误。你必须自己检查那些,例如:

  getAllCountries = async () => {
    try {
      const response = await fetch("https://restcountries.eu/rest/v2/all");
      if (!response.ok) {                                   // ***
        throw new Error("HTTP error " + response.status);   // ***
      }                                                     // ***
      const result = await response.json();
      console.log(result);
      this.countriesList = result;
    } catch (error) {
      console.log(error);
    }
  };