wyf*_*yfy 1 javascript api 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);
}
};
Run Code Online (Sandbox Code Playgroud)
为什么在那里登录了两个 Promise,以及如何访问 PromiseResult。我试过了,console.log(result[0])但没有用
json() 也返回一个承诺,所以:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
旁注:该代码正在成为fetchAPI 枪械的牺牲品:fetch仅拒绝其对网络错误的承诺,而不是 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);
}
};
Run Code Online (Sandbox Code Playgroud)