如何在ionic 4中使用alertcontroller返回承诺?

Kev*_*vin 1 javascript promise typescript ionic-framework ionic4

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

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();
    });
}
Run Code Online (Sandbox Code Playgroud)

seb*_*ras 5

正如你在这里看到的:

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
  });
}
Run Code Online (Sandbox Code Playgroud)

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

var x = await resolveAfter2Seconds(10);
console.log(x); // 10
Run Code Online (Sandbox Code Playgroud)

不把它console.log(x)放在一个.then(() => {...})块中。

f2()因为我们不使用await,应用程序不会等待承诺执行的下一行代码之前得到解决,所以我们必须使用then打印结果在控制台:

resolveAfter2Seconds(10).then(x => {
  console.log(x); // 10
});
Run Code Online (Sandbox Code Playgroud)

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

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();
      });
  });
}
Run Code Online (Sandbox Code Playgroud)

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

private doSomething(): void {

  // ...

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

}
Run Code Online (Sandbox Code Playgroud)