嵌套 async/await 方法的正确方法
Proper way of nesting async/await methods
我有以下场景:
async method1() {
await method2() {...}
method3().then(x => {
await method4().then({...}).catch({...})
}).catch({...})
}
我的节点编译器抛出一个错误,指出 await 不能用于异步方法之外的方法。
错误指向 await method4()
。我可以再次确认我的理解,因为 method4()
执行上下文在 method3()
内,因此,如果我想在 method4()
上使用 await,我需要使 method3()
异步?但这不可能吧?
您必须将 method3().then() 中的回调定义为 async 函数。这样你就可以在其中使用 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 块
中
更简单的方法是不要混合使用 .then()
和 await
,因为这只会让事情变得复杂。而且,一般来说,您不应该将 .then()
处理程序设置为 async
,因为这是没有必要进行上述混合的标志。所以,你可以这样做:
async method1() {
await method2(...)
try {
let x = await method3();
await method4();
} catch(e) {
...
}
}
注意:我没有将对 await method2()
的调用放在 try/catch 中,只是因为您没有在代码中直接处理它的错误,留下任何拒绝返回这也会做的来电者。但是,如果你想在本地处理调用 method2()
的错误,那么也把它放在 try/catch 中:
async method1() {
try {
await method2(...)
let x = await method3();
await method4();
} catch(e) {
...
}
}
注意:这假设所有这些方法都是异步的并且return一个承诺。
我有以下场景:
async method1() {
await method2() {...}
method3().then(x => {
await method4().then({...}).catch({...})
}).catch({...})
}
我的节点编译器抛出一个错误,指出 await 不能用于异步方法之外的方法。
错误指向 await method4()
。我可以再次确认我的理解,因为 method4()
执行上下文在 method3()
内,因此,如果我想在 method4()
上使用 await,我需要使 method3()
异步?但这不可能吧?
您必须将 method3().then() 中的回调定义为 async 函数。这样你就可以在其中使用 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 块
中更简单的方法是不要混合使用 .then()
和 await
,因为这只会让事情变得复杂。而且,一般来说,您不应该将 .then()
处理程序设置为 async
,因为这是没有必要进行上述混合的标志。所以,你可以这样做:
async method1() {
await method2(...)
try {
let x = await method3();
await method4();
} catch(e) {
...
}
}
注意:我没有将对 await method2()
的调用放在 try/catch 中,只是因为您没有在代码中直接处理它的错误,留下任何拒绝返回这也会做的来电者。但是,如果你想在本地处理调用 method2()
的错误,那么也把它放在 try/catch 中:
async method1() {
try {
await method2(...)
let x = await method3();
await method4();
} catch(e) {
...
}
}
注意:这假设所有这些方法都是异步的并且return一个承诺。