javascript - 离子确认警报:在继续之前等待点击警报
问题描述
我有一个运行一些任意代码的函数,称为calculate()
. 我有一个if
条件,如果是,true
我提出一个离子确认警报。
我可以弹出确认警报,但是,我正在尝试使用 async/await 来等待确认中的响应,但是我对 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()
fn 的其余部分继续。我希望它等待确认响应。
关于如何实现这一目标的任何想法?
解决方案
我想到了!我需要首先将 await 设置为一个常量,然后将对话框包装在一个 Promise 中,而不是为每个响应返回一个单独的 Promise。
import { AlertController } from '@ionic/angular';
export class Calculator {
constructor(private alertController:AlertController) {}
async calculate() {
// If my condition is true.
if (true) {
// show the user a confirm alert.
const confirmation = await this.warn();
// break out of function since they hit cancel.
if (!confirmation) return;
}
// The user hit Okay, continue with this function.
}
async warn() {
return new Promise(async (resolve) => {
const confirm = await this.alertController.create({
header: 'confirm',
message: 'my message',
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
return resolve(false);
},
},
{
text: 'OK',
handler: () => {
return resolve(true);
},
},
],
});
await confirm.present();
});
}
}
推荐阅读
- c - 当递归函数在c中达到高深度时停止递归函数
- powershell - 用蛋糕可以轻松完成什么家务,但使用 Powershell + MSBuild 却很痛苦?
- javascript - Reactjs - 如何将数组传递给函数?
- java - JavaFX - 如何修复“fx:控制器只能应用于根元素”
- angular - 角度解析 uint8Array 对对象数组的响应
- tensorflow - Keras Lambda 层何时生成随机数?
- python-3.x - Matplotlib RuntimeError:使用 MultipleLocator 时超出 Locator.MAXTICKS
- laravel - Laravel Nova 删除资源
- javascript - Express.js 应用程序部署:无效命令“PassengerAppRoot”,可能拼写错误或由未包含在服务器配置中的模块定义
- python - Int 对象没有属性“__getitem__”