javascriptnode.jsasynchronouspromiseasync-await

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;
  }

Solution

  • An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

    As you can see from below example that you can use two ways to handle await result and errors,The keyword await makes JavaScript wait until that promise settles and returns its result (One you get from resolved promise).So as such there is no harm (I don't fully understand what you refer as harm here).

    function returnpromise(val) {
      return new Promise((resolve, reject) => {
        if (val > 5) {
          resolve("resolved"); // fulfilled
        } else {
          reject("rejected"); // rejected
        }
      });
    }
    
    //This is how you handle errors in await
    async function apicall() {
      try {
        console.log(await returnpromise(5))
      } catch (error) {
        console.log(error)
      }
    }
    
    async function apicall2() {
      let data = await returnpromise(2).catch((error) => {
        console.log(error)
      })
    }
    
    apicall2();
    apicall();

    For further reference have a look at-MDN DOCS