2017-10-16 89 views
5

我有一个使用ionViewCanLeave() navGuard显示确认消息的Ionic 2应用程序。这工作正常;用户会看到一个确认对话框,如果他们想要,可以选择不离开。下面是它的代码:如何嵌套2个承诺并让ionViewCanLeave等待结果?

// 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()不等待存储调用运行,因为它是异步的。

我该如何解决这个问题?

+0

更多信息不相关的问题:你确定了'if'条件是正确的?它不应该是一个'||'而不是一个'&&'?只是猜测的变量的名称... – trincot

+0

我只是想说,你的问题帮助我防止页面离开使用alerCtrl,这个问题花了我4天解决,谢谢 – George

回答

3

您需要返回承诺:

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

当然...这是排序它。不能相信我错过了:( – Mike

0

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