Home > Article > Web Front-end > Is Using Async/Await with .then() and .catch() a Good Practice in JavaScript?
Using Async/Await and .then() Together in JavaScript
The question arises whether it's detrimental to combine async/await and .then().catch() in the following manner:
<code class="javascript">async apiCall(params) { var results = await this.anotherCall() .then(results => { //do any results transformations return results; }) .catch(error => { //handle any errors here }); return results; }</code>
Instead of using async/await and try/catch, the author suggests utilizing async/await and .catch() to condense the code. Here's an example:
<code class="javascript">async function asyncTask() { throw new Error('network') } async function main() { const result = await asyncTask().catch(error => console.error(error)); console.log('result:', result) } main();</code>
By employing .catch(), error handling is achieved without the necessity of a try/catch block, streamlining the code structure.
The above is the detailed content of Is Using Async/Await with .then() and .catch() a Good Practice in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!