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将不会捕获异步操作中发生的异常。
| 归档时间: |
|
| 查看次数: |
17531 次 |
| 最近记录: |