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
await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have an effect on it.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.
If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With