Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using async await and .then together

Is there any harm in using async/await and .then().catch() together such as:

async apiCall(params) {     var results = await this.anotherCall()       .then(results => {         //do any results transformations         return results;       })       .catch(error => {         //handle any errors here       });     return results;   } 
like image 270
PixelPaul Avatar asked Mar 06 '19 09:03

PixelPaul


People also ask

Can I use .then with async await?

Using `then()` vs Async/Await in JavaScript. When making async requests, you can either use then() or async/await. Async/await and then() are very similar. The difference is that in an async function, JavaScript will pause the function execution until the promise settles.

Can you mix async await and promises?

Async/await is not meant to replace promises -- it's actually syntactic sugar for creating functions that return and wait for promises. In this video, you'll learn how to use a combination of promises and async/await to produce code that's more readable.

Does await wait for then?

The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place. Otherwise, it returns the result.

Can we use await with promise?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.


1 Answers

I always use async/await and .catch() instead of using async/await and try/catch to make code compactly.

async function asyncTask() {   throw new Error('network') } async function main() {   const result = await asyncTask().catch(error => console.error(error));   console.log('result:', result) }  main();

If you want to get a fallback value when an error happened, you can ignore the error and return a value inside the .catch() method

async function asyncTask() {   throw new Error('network') } async function main() {   const result = await asyncTask().catch(_ => 'fallback value');   console.log('result:', result) }  main();
like image 91
slideshowp2 Avatar answered Oct 05 '22 23:10

slideshowp2