Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

i.e.

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

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.

like image 450
williamsi Avatar asked May 27 '18 22:05

williamsi


People also ask

Can you have multiple awaits in one async function?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

Is try catch necessary for async await?

No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!

Can we use await in catch block?

C# await is a keyword. It is used to suspend execution of the method until the awaited task is complete. In C# 6.0, Microsoft added a new feature that allows us to use await inside the catch or finally block. So, we can perform asynchronous tasks while exception is occurred.

How do I catch exceptions with async await?

catch (in combination with async functions) and the . catch() approaches to handle errors for asynchronous code. When returning a promise within a try block, make sure to await it if you want the try... catch block to catch the error.


1 Answers

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.

like image 184
traktor Avatar answered Sep 21 '22 17:09

traktor