Search code examples
javascriptes6-promise

Proper way of nesting async/await methods


I have the following scenario:

async method1() {
  await method2() {...}

  method3().then(x => {
    await method4().then({...}).catch({...})
  }).catch({...})
}

My node compiler threw an error saying that await cannot be used on a method outside of an async method. The error was pointed at the await method4(). May I just double confirm my understanding that because the method4() execution context is within method3(), therefore, if i wanted to use an await on method4(), i need to make method3() async? But then that is not possible right?


Solution

  • The easier way is to not mix .then() and await as it just complicates things. And, in general, you should NOT make a .then() handler be async as that's a sign of the above mixing which is not necessary. So, you can just do this:

    async method1() {
      await method2(...)
      try {
          let x = await method3();
          await method4();
      } catch(e) {
          ...
      }
    }
    

    Note: I did not put the call to await method2() inside the try/catch only because you weren't directly handling errors on it in your code, leaving any rejections in it to go back to the caller which this will also do. But, if you want to locally handle errors from the call to method2(), then put it inside the try/catch also:

    async method1() {
      try {
          await method2(...)
          let x = await method3();
          await method4();
      } catch(e) {
          ...
      }
    }
    

    Note: This assumes that all these methods are asynchronous and return a promise.