首页 > 解决方案 > 离子确认警报:在继续之前等待点击警报

问题描述

我有一个运行一些任意代码的函数,称为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 的其余部分继续。我希望它等待确认响应。

关于如何实现这一目标的任何想法?

标签: javascriptangularionic-frameworkecmascript-6

解决方案


我想到了!我需要首先将 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();
    });
  }
}

推荐阅读