简体   繁体   English

在异步功能中返回或跳过捕获

[英]Return or skip from catch in async function

I have a async function whose output (resolve/reject) I translate with then/catch. 我有一个异步函数,其输出(解析/拒绝)可以通过then / catch转换。

I want to end the outer function with return but I can only return within catch somehow. 我想用return结束外部函数,但是我只能以某种方式在catch中返回。

How can I skip/quit/return on the outside of catch or await? 如何在捕获或等待的外部跳过/退出/返回?

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;
})

You can have the .then and .catch return something meaningful that distinguishes them, and then test that distinguishing factor. 你可以有.then.catch返回一些有意义区分它们,然后测试区分因素。 For example: 例如:

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(...)

Note that if you're using await , it might make a bit more sense to use try/catch rather than .then s and await s: 请注意,如果您使用的是await ,则使用try/catch而不是.then s await可能会更有意义:

try {
  const authorizedUser = await this.authService.auth(this.oldUser)
  // do stuff with authorizedUser
  // rest of the code that depends on the first request being successful goes here
  const newAuthorizedUser = await this.authService.auth(this.newUser);
  // do stuff with newAuthorizedUser
} catch(err) {
    // handle errors, if needed
    return;
}
private async authenticate(oldUser: User) {
    try {
        await this.authService.auth(this.oldUser).toPromise();            
        return;
    } catch (reject) {
        return;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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