首页 > 解决方案 > 嵌套异步/等待方法的正确方法

问题描述

我有以下情况:

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

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

我的节点编译器抛出一个错误,说 await 不能用于异步方法之外的方法。错误指向await method4(). 我可以再次确认我的理解,因为method4()执行上下文在内部method3(),因此,如果我想使用 await on method4(),我需要进行method3()异步?但那是不可能的吧?

标签: javascriptes6-promise

解决方案


您必须将 method3().then() 内的回调定义为异步函数。这样您就可以在其中使用await

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

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

此外,如果您使用 then 和 catch,则无需使用 await。

您可以将其转换为,

const res = await method4();

变量res将包含结果或错误消息。此外,最好将 await 语句包装在 try-catch 块中


推荐阅读