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; }
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With