我有一个运行任意代码的函数,名为calculate()
。我有一个if
条件,如果它是true
,我会弹出一个ionic确认警报。
我可以让确认警报弹出,但是我试图使用async/await等待确认中的响应,但是我的理解可能是错误的。这基本上是我正在做的:
import { AlertController } from '@ionic/angular';
export class Calculator {
private cancelResults:boolean = false;
constructor(private alertController:AlertController) {}
async calculate() {
// If my condition is true.
if (true) {
// show the user a confirm alert.
await this.warn();
// break out of function since they hit cancel.
if (this.cancelResults) return;
}
// The user hit Okay, continue with this function.
}
async warn() {
const alert = await this.alertController.create({
header: 'confirm',
message: 'my message',
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: (blah) => {
console.log('they hit cancel');
this.cancelResults = true;
return new Promise(resolve => setTimeout(resolve, 2000));
}
}, {
text: 'Okay',
handler: () => {
console.log('they hit ok');
return new Promise(resolve => setTimeout(resolve, 2000));
}
}
]
});
await alert.present();
}
}
当确认框弹出时,calculate()
函数的其余部分继续执行。我希望它等待确认响应。
有任何想法如何实现这一点吗?