簡體   English   中英

switch case 語句中的異步等待不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM