【问题标题】:How to return a promise with alertcontroller in ionic 4?如何在 ionic 4 中使用 alertcontroller 返回承诺?
【发布时间】:2019-10-31 10:18:57
【问题描述】:

我正在尝试将此 ionic 3 代码转换为 ionic 4,但我不知道承诺如何在 ionic 4 上发挥作用。我尝试查看文档,但找不到任何承诺的解决方案

async generateAlert(header, message, ok, notOk): Promise<boolean> {
    return new Promise((resolve, reject) => {
        let alert = await this.alertController.create({
            header: header,
            message: message,
            buttons: [
                {
                    text: notOk,
                    handler: _=> reject(false)
                },
                {
                    text: ok,
                    handler: _=> resolve(true)
                }
            ]
        })
        await alert.present();
    });
}

【问题讨论】:

  • 拜托,你能告诉你你想做什么吗?

标签: javascript typescript ionic-framework promise ionic4


【解决方案1】:

如你所见here

await 运算符用于等待一个 Promise。

所以await 只是另一种使用 Promise 的方式,如下例所示:

// Method that returns a promise
private resolveAfter2Seconds(x: number): Promise<number> { 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

// Using await
private async f1(): Promise<void> {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}

// Not using await
private f2(): void {
  resolveAfter2Seconds(10).then(x => {
    console.log(x); // 10
  });
}

f1(){...} 中,您可以看到应用程序将如何在执行下一行代码之前等待promise 被解析。这就是为什么你可以做类似的事情

var x = await resolveAfter2Seconds(10);
console.log(x); // 10

没有将 console.log(x) 放在 .then(() =&gt; {...}) 块中。

f2()中,由于我们不使用await,所以应用程序不会等待promise被解析后才执行下一行代码,所以我们必须使用then将结果打印在控制台:

resolveAfter2Seconds(10).then(x => {
  console.log(x); // 10
});

话虽如此,如果您只想创建一个显示警报并在用户选择ok/notOk 按钮时返回真/假的方法,您可以执行以下操作(不使用 @ 987654334@):

private generateAlert(header: string, message: string, ok: string, notOk: string): Promise<boolean> {
  return new Promise((resolve, reject) => {
    // alertController.create(...) returns a promise!
    this.alertController
      .create({
        header: header,
        message: message,
        buttons: [
          {
            text: notOk,
            handler: () => reject(false);
          },
          {
            text: ok,
            handler: () => resolve(true);
          }
        ]
      })
      .then(alert => {
        // Now we just need to present the alert
        alert.present();
      });
  });
}

那么你可以像这样使用那个方法

private doSomething(): void {

  // ...

  this.generateAlert('Hello', 'Lorem ipsum', 'Ok', 'Cancel').then(selectedOk => {
    console.log(selectedOk);
  });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-25
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2016-06-15
    相关资源
    最近更新 更多