javascript - 嵌套异步/等待方法的正确方法
问题描述
我有以下情况:
async method1() {
await method2() {...}
method3().then(x => {
await method4().then({...}).catch({...})
}).catch({...})
}
我的节点编译器抛出一个错误,说 await 不能用于异步方法之外的方法。错误指向await method4()
. 我可以再次确认我的理解,因为method4()
执行上下文在内部method3()
,因此,如果我想使用 await on method4()
,我需要进行method3()
异步?但那是不可能的吧?
解决方案
您必须将 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 块中
推荐阅读
- node.js - FFmpeg image2pipe 写缓冲区等到完成
- javascript - 使用 codeigniter ajax 中的按钮打开模式时用户状态更改
- c++ - OpenGL - 在同一个对象上混合两个纹理
- java - 在java上将epoch json格式字符串转换为日期
- c# - 如何使用 Linq 过滤具有子列表的项目列表以删除 C# 中不允许的项目?
- postgresql - 如何减小 PostgreSQL 数据库大小
- android - 找不到参数的方法 implementation() [DefaultExternalModuleDependency{group='com.google.firebase', name='firebase-bom', version='*
- mysql - 如何将日期时间值从 0000-00-00 00:00:00 值更新为 null
- linux - Linux 内核 insmod 失败并出现错误 Invalid parameters
- r - 使用反应值更新数据帧的多个值