异步async / await函数中的正确错误处理

时间:2020-01-29 20:58:36

标签: javascript async-await

对于在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和{{ 1}},对吧?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

这是调试工具,可向您显示请求失败,而不是表明未处理失败。

答案 1 :(得分:0)

错误显示cannot read property '1' of undefined

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]; <----- this is undefined
            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}`);
})

我的猜测是tomorrow在数据初始化之前正在初始化-或data没有密钥consolidate_weather

fetch.then()可能会得到想要的结果


let tomorrow;
return fetch(url).then((result) => {
     const data = JSON.parse(result);
     tomorrow = data.consolidated_weather[1];
     return data;
}, (error) => {
    console.log(`Error .catch()-Statement: ${error}`);
})