首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Async/Await捕获错误

使用Async/Await捕获错误
EN

Stack Overflow用户
提问于 2019-09-25 21:44:40
回答 1查看 62关注 0票数 4

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

代码语言:javascript
复制
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;
        });
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-25 21:47:12

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

代码语言:javascript
复制
const responseOne = await one(errors);
const responseTwo = await two(errors);
const responseThree = await three(errors);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58099856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档