'async await in switch case statement does not work

can we wait for the resolution of a promise within switch case statement, using the keyword await? in my angular component I have the following code which crashes my application.

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

After several tests, the error seems to me to come from lines starting with await. Can you tell me what's wrong please. I would like this.dbService.addOrderPaymentResult(ProcessResult.done, this.printerVMService.getSessionId()) which returns an observable is executed synchronously before going to this.router.navigate(['welcome/paying/paying_accepted']); that's why i chose to use toPromise() and await



Solution 1:[1]

Yes, you can:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TKoL