我对在javascript中async
函数中处理错误的正确方法有些困惑。
async function getWeatherAW(woeid) {
try {
const result = await fetch(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/${woeid}/`);
const data = await result.json();
const tomorrow = data.consolidated_weather[1];
return data;
} catch(error) {
console.log(`Error catch-Statement: ${error}`);
}
}
const wrongData = 3442;
getWeatherAW(wrongData)
.then(data => {
console.log(data);
})
.catch(error => {
console.log(`Error .catch()-Statement: ${error}`);
})
此代码最终给出了此result。我很好奇为什么即使触发了catch语句,也会在控制台上打印出404
错误。
最好不要返回async
函数的结果,而是继续执行该函数吗?我的意思是,首先出现错误时,then-block中的数据似乎未定义..如果我需要更频繁地调用该函数,则不必总是写then
和catch
,对吗?
提前感谢!
它抛出404错误,因为它异步加载文件,但没有异步运行try-catch块。 try-catch块将像普通的javascript一样运行,并且不会在成功或捕获之前等待请求完成。由于文件不存在,因此我无法防止该错误。