【发布时间】:2019-06-06 18:37:13
【问题描述】:
我有一个函数可以运行一些任意代码,称为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 的其余部分继续。我希望它等待确认响应。
关于如何实现这一点的任何想法?
【问题讨论】:
-
本教程应该可以帮助你理解 async await youtube.com/watch?v=vn3tm0quoqE
-
感谢@JuanLozoya,这是一个做得很好的视频并解释了很多事情
标签: javascript angular ionic-framework ecmascript-6