Home > Web Front-end > JS Tutorial > Is Using Async/Await with .then() and .catch() a Good Practice in JavaScript?

Is Using Async/Await with .then() and .catch() a Good Practice in JavaScript?

Linda Hamilton
Release: 2024-11-03 05:49:30
Original
324 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template