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

时间:2019-01-19 17:16:33

标签: javascript angularjs angular asynchronous

我有一个异步函数,其输出(解析/拒绝)可以通过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;
})

2 个答案:

答案 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;
    }
}