javascript - 异步 async/await 函数中的正确错误处理
问题描述
async
我对在 javascript中处理函数中的错误的正确方法有点困惑。
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}`);
})
这段代码最终给出了这个结果。我很好奇为什么即使触发了 catch 语句,也会将404
错误打印到控制台..
不从函数返回结果async
而是在函数中继续会更好吗?我的意思是当首先发生错误时,then-block 中的数据似乎是未定义的。如果我需要更频繁地调用该函数,我并不总是需要编写then
and catch
,对吗?
提前致谢!
解决方案
无论是否处理了错误,控制台都会为所有失败的请求打印 404 消息。
它是一种调试帮助,向您显示请求失败,而不是表示未处理失败。
推荐阅读
- r - R:通过引入数字来选择选项
- excel - 标识一行以格式化文本
- powershell - 检查列的数量和名称,如果错误则停止脚本
- python - 在日期时间索引中查找缺失时段的开始和结束日期
- python - 如何在python中解析html表
- c++ - 为后台任务设置 CPU Affinity 并阻止 CPU 使用
- python - 在python中将字符串日期转换为long
- python - OpenAI Gym + WSL2 + VcXsrv 移动窗口问题
- javascript - 在单组件苗条中导入传单
- apache-spark - 将值重置为配置“spark.executor.instances”