简体   繁体   中英

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?

You have to define the callback inside method3().then() as async function. So that you can use await inside of that.

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

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

Also, you need not to use await, if you are using then and catch.

You can convert it to,

const res = await method4();

The variable res will contain result or error msg. Also it's better to wrap the await statements inside try-catch block

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM