问题描述
即
async asyncfunction(){
try{
await method1();
await method2();
}
catch(error){
console.log(error);
}
}
给出method1()和method2()是异步函数.每个await方法是否应该有一个try/catch块?有没有更干净的方式来写这个?我正在尝试避免".then"和".catch"链接.
Given method1() and method2() are asynchronous functions. Should there be a try/catch block for each await method? Is there an even cleaner way to write this? I'm trying to avoid '.then' and '.catch' chaining.
推荐答案
使用一个包含多个 await
操作的try/catch块就可以了.
Using one try/catch block containing multiple await
operations is fine.
await
操作符存储其父 async
函数的执行上下文,并返回到事件循环.当调用 await
运算符并返回其稳定状态和其操作数的值时,将继续执行.
The await
operator stores its parent async
functions' execution context and returns to the event loop. Execution of the await
operator resumes when it is called back with the settled state and value of its operand.
恢复后, await
恢复先前保存的执行上下文,并作为 await
表达式的结果返回操作数promise的已实现值,或者抛出被拒绝的拒绝原因操作数.
Upon resumption, await
restores the previously saved execution context and returns the operand promise's fulfilled value as the result of the await
expression, or throws the rejection reason of a rejected operand.
在保存和恢复之前和之后, try/catch
块调用是执行上下文的一部分.因此,多个 await
操作不会干扰它们共享的外部 try
块的行为. catch
块将以 try
块中被拒绝的任何承诺的拒绝原因被调用.
The try/catch
block invocation is part of the execution context both before and after being saved and restored. Hence multiple await
operations do not disturb the behavior of an outer try
block they share. The catch
block will be invoked with the rejection reason of any promise awaited in the try
block that is rejected.
这篇关于我可以在异步函数的try/catch块中使用多个"await"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!