The Official Ionic Blog

Build amazing native and progressive web apps with HTML5

Ionic 2 offers a powerful NavController that allows you to show new pages, alerts, modals, and even loading indicators. But what happens when you need to coordinate multiple events around a single API call? All of these event are asynchronous and could return at any given time, so how can we put it all together?

In this screencast, we’ll look at a situation just like this and figure out what our best practices should be.

The sample code used in this screencast can be found here.

  callLoad() {
    let alert = Alert.create({
      title: 'Async',
      message: '',
      buttons: [{
        text: 'Ok',
        handler: () => {
          this.data.load().then(()=>{
            alert.dismiss().then(()=>{
              this.nav.pop();
            })
          })
          return false;
        }
      }]
    });
    this.nav.present(alert);
  }
  • Militello Salvatore

    Ok, but so it is necessary to tap the OK button. Is it possible to do the same in a Loading component and close it only after the async call is terminated?

  • Bengt Weiße

    you should build a promise chain instead of nesting them. Promises are there to avoid a callback pyramids of doom 😉

    • http://www.alexweber.com.br/ Alex Weber

      Agreed, the code could be made a bit more elegant like that:

      “`
      handler: () => {
      return this.data.load().then(()=>{
      return alert.dismiss();
      }).then(() => {
      this.nav.pop();
      });
      return false;
      }
      “`

      • Kamil Rykowski

        So that’s the way to handle promise chain. Thanks man!

      • Mike Hartington

        Not really the point…but ok.