我有一个异步函数,其输出(解析/拒绝)可以通过then / catch转换。
我想以return结尾外部函数,但是我只能以某种方式在catch中返回。
如何在catch之外等待/跳过/退出/返回?
await this.authService.auth(this.oldUser).then( resolve => {
//went in authService and resolve can be used
}).catch( reject => {
//in catch as authService rejected and want to return to outer
//function
return;
})
//Second attempt should only be done if first attempt "resolved"
await this.authService.auth(this.newUser).then( resolve => {
}).catch( reject => {
return;
})
答案 0 :(得分:0)
您可以让.then
和.catch
返回有意义的东西来区分它们,然后测试该区分因素。例如:
const result = await this.authService.auth(this.oldUser).then((authorizedUser) => {
// do stuff with authorizedUser
return authorizedUser;
}).catch((err) => {
// handle errors, if needed
return { err };
});
if (result.err) {
// there was en error, return early:
return;
}
// rest of the code that depends on the first request being successful goes here
await this.authService.auth(this.newUser).then(...)
请注意,如果您使用的是await
,则使用try/catch
而不是.then
的和 {{1} } s:
await
答案 1 :(得分:0)
private async authenticate(oldUser: User) {
try {
await this.authService.auth(this.oldUser).toPromise();
return;
} catch (reject) {
return;
}
}