[英]async await in switch case statement don't work
我们可以使用关键字 await 在 switch case 语句中等待承诺的解决吗? 在我的角度组件中,我有以下代码使我的应用程序崩溃。
switch (this.status) {
case 'opened':
break;
case 'payed':
this.getIntervalStatusSubscription.unsubscribe();
this.localStorageService.storePaymentIsMade(true);
await this.dbService.addOrderPaymentResult(ProcessResult.done, this.printerVMService.getSessionId()).toPromise();
this.router.navigate(['welcome/paying/paying_accepted']);
break;
case 'closed':
this.getIntervalStatusSubscription.unsubscribe();
this.paymentSessionIsClosed = true;
await this.dbService.addOrderPaymentResult(ProcessResult.error, this.printerVMService.getSessionId()).toPromise();
this.router.navigate(['welcome']);
break;
case 'used':
this.getIntervalStatusSubscription.unsubscribe();
this.router.navigate(['welcome']);
break;
default:
console.error('status don\'t exist');
this.utils.displayAlertError(this.device.getIntervalStatus);
this.router.navigate(['welcome']);
}
经过几次测试,在我看来,错误似乎来自以await
开头的行。 你能告诉我有什么问题吗? 我想要this.dbService.addOrderPaymentResult(ProcessResult.done, this.printerVMService.getSessionId())
返回一个 observable 在进入this.router.navigate(['welcome/paying/paying_accepted']);
之前同步执行this.router.navigate(['welcome/paying/paying_accepted']);
这就是为什么我选择使用toPromise()
并await
是的你可以:
async function trySwitch(status) { switch(status) { case 'opened': console.log('1'); break; case 'closed': console.log('2'); await new Promise(r => setTimeout(r, 1000)); console.log('3'); break; } } trySwitch('opened'); trySwitch('closed');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.