【问题标题】:How can I nest 2 promises and have ionViewCanLeave wait for the outcome?如何嵌套 2 个承诺并让 ionViewCanLeave 等待结果?
【发布时间】:2018-03-28 02:35:20
【问题描述】:

我有一个 Ionic 2 应用程序,它使用 ionViewCanLeave() navGuard 来显示确认消息。这很好用;用户会看到一个确认对话框,如果他们愿意,可以选择不离开。这是它的代码:

  // About to leave
  ionViewCanLeave() { 
    if(!this.allowedToLeave) {
      return new Promise((resolve, reject) => {
        let confirm = this.alertCtrl.create({
          title: 'Are you sure?',
          message: 'Are you sure?',
          buttons: [{
            text: 'OK',
            handler: () => {
              this.allowedToLeave = true;
              resolve();
            },
          }, {
            text: 'Cancel',
            handler: () => {
              reject();
            }
          }],
        });
        confirm.present(); 
      });
    }
  }

我现在需要检查来自storage 的附加变量。为了得到那个变量,我需要一个承诺。我的代码如下:

  // About to leave
  ionViewCanLeave() {
    this.storage.get('safe_to_leave').then((val) => {
      this.safeToLeave = val;

      if(!this.allowedToLeave && !this.safeToLeave) {
        return new Promise((resolve, reject) => {
          let confirm = this.alertCtrl.create({
            title: 'Are you sure?',
            message: 'Are you sure?',
            buttons: [{
              text: 'OK',
              handler: () => {
                this.allowedToLeave = true;
                resolve();
              },
            }, {
              text: 'Cancel',
              handler: () => {
                reject();
              }
            }],
          });
          confirm.present(); 
        });
      }
    });
  }

这里发生的情况是,页面从导航堆栈中弹出,然后显示确认对话框。看起来ionViewCanLeave() 没有等待存储调用运行,因为它是异步的。

我怎样才能解决这个问题?

【问题讨论】:

  • 与您的问题无关:您确定if 条件正确吗?不应该是|| 而不是&&?只是通过变量的名称来猜测......
  • 我只想说你的问题帮助我防止了使用alerCtrl的页面离开,这个问题我花了4天时间才解决,谢谢

标签: javascript angular ionic-framework ionic2 promise


【解决方案1】:

你需要返回承诺:

return this.storage.get( /* ...etc
^^^^^^                             */

【讨论】:

  • 当然……这就是它的排序。不敢相信我错过了:(
【解决方案2】:

请使用 Promise.all() 方法查看队列承诺。

更多信息link

let promises = [];

promises.push(asynchroniousFunction);
promises.push(AnotherAsynchroniousFunction);

Promise.all(promises).then((results) => {
  console.log('Data from first method', results[0]);
  console.log('Data from second method', results[1]);
}).catch((error) => {
  console.log('Error from first method', error[0]);
  console.log('Error from second method', error[1]);
});

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2019-06-30
    • 2018-05-05
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多