【发布时间】:2020-05-15 10:42:36
【问题描述】:
我对在 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块中的数据似乎是未定义的。如果我需要更频繁地调用该函数,我并不总是需要编写then和catch,对吧?
提前致谢!
【问题讨论】:
-
"发生错误时,then 块中的数据似乎未定义" - 那是因为您的
try/catch正在处理异常,然后返回undefined。你也可以返回其他东西。但是拥有undefined似乎不是很有用,每次都需要if (data !== undefined),拒绝承诺并正确处理错误似乎更好。 -
请参阅this thread,了解来自 fetch 的浏览器日志记录错误。