繁体   English   中英

我什么时候应该使用 try catch 而不是 then catch?

[英]When should I use try catch instead of then catch?

这个问题很简单,但我在任何地方都没有找到答案。

我什么时候应该使用try catch? 在下面的代码中,我使用 try catch 来处理请求的返回:

async findUsers() {
    this.loading = true;

    try {
        const [users, count] = await this.api.get('/users/list');

        this.users = users;
        this.totalPages = Math.ceil(parseInt(count) / 10);
    }
    catch (error) {
        this.Messages.requestFailed(error);
    }
    finally {
        this.loading = false;
    }
}

使用 then(...).catch(...) 会是一个好习惯吗?

不同之处在于你如何处理 Promise。

如果您使用await来处理 Promise,那么您将其包装在try/catch中。 await视为一种使异步操作在语义上类似于同步操作的方法。

但是,如果您使用await而是通过将 .then( .then()附加到 Promise 来处理它,那么您将在该链上附加.catch()以从异步操作中捕获故障。

因为如果不等待该操作, try/catch不会捕获异步操作中发生的异常。

当您使用承诺(异步操作)时,您需要在发生错误时处理异常。 所以在这种情况下你可以使用.then().catch(err) {}

当您有同步代码时,请使用try/catch进行异常处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM