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

Tch*_*loh 20 javascript asynchronous promise

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

我什么时候应该使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*vid 22

区别在于你如何传递 Promise。

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

但是,如果您使用awaitPromise,而是通过附加.then()到 Promise 来处理 Promise,那么您可以将 a 附加.catch()到该链以捕获异步操作中的失败。

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

  • @MatheusSantos:你可能对整件事想得太多了。这只是你如何处理 Promise 的问题。如果等待,您可以使用普通的 try/catch。如果回调函数没有等待和处理它,那么您需要使用 .catch() 作为回调链的一部分。就这样。 (2认同)