How can I nest 2 promises and wait for ionViewCanLeave for the result?

I have an Ionic 2 application that uses ionViewCanLeave() navGuard to display a confirmation message. This works great; the user displays a confirmation dialog box and may not leave it if he wants. Here is the code for it:

  // 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(); }); } } 

Now I need to check the extra variable here from storage . To get this variable, I need a promise. My code is as follows:

  // 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(); }); } }); } 

However, what happens here is that the page is pushed out of the navigation stack, and then a confirmation dialog is displayed. It seems that ionViewCanLeave() not waiting for a call to the storage call, since it is asynchronous.

How can I get around this?

+5
source share
2 answers

You need to return the promise:

 return this.storage.get( /* ...etc ^^^^^^ */ 
+3
source

Please take a look at the order of promises using the Promise.all () method.

Additional information on the 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]); }); 
0
source

Source: https://habr.com/ru/post/1272667/


All Articles