首页 > 解决方案 > 异步 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 中的数据似乎是未定义的。如果我需要更频繁地调用该函数,我并不总是需要编写thenand catch,对吗?

提前致谢!

标签: javascriptasync-await

解决方案


无论是否处理了错误,控制台都会为所有失败的请求打印 404 消息。

它是一种调试帮助,向您显示请求失败,而不是表示未处理失败。


推荐阅读