使用异步/等待捕获错误

时间:2019-09-25 13:44:39

标签: javascript async-await

我有一部分代码对不同的端点进行了几次API调用,我想知道这些调用是否失败,以便显示适当的错误消息。现在,如果one()中发生错误,它将阻止其他所有调用的发生,但这不是我想要的;如果发生错误,我希望它填充errors对象并让程序继续运行。

async function gatherData() {
    let errors = { one: null, two: null, three: null };

    const responseOne = await one(errors);
    const responseTwo = await two(errors);
    const responseThree = await three(errors);

    if (!_.isNil(errors.one) || !_.isNil(errors.two) || !_.isNil(errors.three)) {
        // an error exists, do something with it
    } else {
        // data is good, do things with responses
    }
}

gatherData();

async function one(errors) {
    await axios
        .get("https://jsonplaceholder.typicode.com/comment")
        .then(res => {
            return res;
        })
        .catch(err => {
            errors.one = err;
            return err;
    });
}

async function two(errors) {
    await axios
        .get("https://jsonplaceholder.typicode.com/comments")
        .then(res => {
            return res;
        })
        .catch(err => {
            errors.two = err;
            return err;
    });
}

async function three(errors) {
    await axios
        .get("https://jsonplaceholder.typicode.com/comments")
        .then(res => {
            return res;
        })
        .catch(err => {
            errors.three = err;
            return err;
        });
}

1 个答案:

答案 0 :(得分:3)

如果将errors传递给async函数,则将errors对象作为参数传递

const responseOne = await one(errors);
const responseTwo = await two(errors);
const responseThree = await three(errors);