Can I use multiple 'await' in an async function's try/catch block?

前端 未结 1 1506
自闭症患者
自闭症患者 2021-02-13 05:23

i.e.

async asyncfunction(){
  try{
    await method1();
    await method2();
  }
  catch(error){
    console.log(error);
  }
}

Given method1()

1条回答
  •  庸人自扰
    2021-02-13 06:08

    Using one try/catch block containing multiple await operations is fine.

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题