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

Signup for the Ionic Newsletter to get the latest news and updates!

  • 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.

  • Haider Rasool

    Your Promise code helped me made one. Thanks 🙂

  • pslvseo a2

    While the relationship of stocks to the dollar has not always been “down dollar = up stocks” it has been this year. And in this market, that which gets rewarded gets repeated until someone’s throat gets ripped out.
    At times it has been that a strong dollar meant a strong America and a strong economy. All rules of logic are gone due to the oligarchs running the government.
    http://www.screencast.com/