代码之家  ›  专栏  ›  技术社区  ›  Mike

我怎样才能做出两个承诺,让IonviewCan等待结果?

  •  5
  • Mike  · 技术社区  · 7 年前

    我有一个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(); 
            });
          }
        });
      }
    

    然而,这里发生的事情是,页面从导航堆栈弹出,然后显示确认对话框。看起来像 不是等待存储调用运行,因为它是异步的。

    我怎么才能避开这个?

    2 回复  |  直到 7 年前
        1
  •  3
  •   trincot Jakube    7 年前

    你需要回报承诺:

    return this.storage.get( /* ...etc
    ^^^^^^                             */
    
        2
  •  0
  •   JoeriShoeby    7 年前

    请看排队承诺,使用承诺。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]);
    });