# Loading controller await problem

**URL:** <https://forum.ionicframework.com/t/loading-controller-await-problem/194089>\
**Category:** Ionic Framework\
**Created:** [August 7, 2020, 10:35am UTC](https://forum.ionicframework.com/t/loading-controller-await-problem/194089 "2020-08-07T10:35:43Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![enfix](https://avatars.discourse-cdn.com/v4/letter/e/e79b87/32.png) [@enfix](https://forum.ionicframework.com/u/enfix)\
**Post date:** [August 7, 2020, 10:35am UTC](https://forum.ionicframework.com/t/loading-controller-await-problem/194089/1 "2020-08-07T10:35:43Z")

</div>

In my ngOnInit page I call a function to present a Loading and then call my service to load data.  
The problem is that the service call ends before the loading starts.  
How is it possibile with await?

```auto
loading: any;
...
ngOnInit() { 
    this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
      this.loading.dismiss();
    }, ()=>{
      this.loading.dismiss();
    })
  }

  async presentLoading() {
    this.loading = await this.loadingController.create({
      message: 'Loading...',
      duration: 20000
    });
    console.log('presentLoading')
    await this.loading.present();
  }

```

In console i can see:

```auto
dismiss
ERROR TypeError: Cannot read property 'dismiss' of undefined....
presentLoading

```

I’m using Ionic4.

---

<div class="post-metadata">

**Author:** ![vickypryma](https://avatars.discourse-cdn.com/v4/letter/v/8edcca/32.png) [@vickypryma](https://forum.ionicframework.com/u/vickypryma)\
**Post date:** [August 7, 2020, 12:55pm UTC](https://forum.ionicframework.com/t/loading-controller-await-problem/194089/2 "2020-08-07T12:55:53Z")

</div>

You don’t have to put your loading to variable **this.loading**. You can dismiss it just by loading controller.

```auto
this.loadingController.dismiss();

```

And don’t forget to await your **presentLoading**. It is because your service can be running before your loading presented and service ended first.

```auto
async ngOnInit() {
	await this.presentLoading();
	.....
}

```

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [August 7, 2020, 7:41pm UTC](https://forum.ionicframework.com/t/loading-controller-await-problem/194089/3 "2020-08-07T19:41:09Z")

</div>

Or don’t use `async` / `await` in the first place. I think they obscure what is really going on, which can be especially troubling for people getting used to asynchronous programming in general. I think it’s much better in the long run to train yourself to think and write reactively, instead of relying on syntax sugar to perpetuate imperative programming styles that are out-of-place for web apps.

---

<div class="post-metadata">

**Author:** ![Daveshirman](https://avatars.discourse-cdn.com/v4/letter/d/ecd19e/32.png) [@Daveshirman](https://forum.ionicframework.com/u/Daveshirman)\
**Post date:** [August 9, 2020, 1:40am UTC](https://forum.ionicframework.com/t/loading-controller-await-problem/194089/4 "2020-08-09T01:40:25Z")

</div>

Maybe you should edit your comment to include the alternative code snippet you are suggesting enfix should use? It think it would be helpful.

---

<div class="post-metadata">

**Author:** ![enfix](https://avatars.discourse-cdn.com/v4/letter/e/e79b87/32.png) [@enfix](https://forum.ionicframework.com/u/enfix)\
**Post date:** [August 10, 2020, 9:02am UTC](https://forum.ionicframework.com/t/loading-controller-await-problem/194089/5 "2020-08-10T09:02:27Z")

</div>

I know the solution is to use a Promise and put everything inside the then() but I wanted to understand how it works and why it doesn’t work with async

---

<div class="post-metadata">

**Author:** ![rapropos](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/rapropos/32/100227_2.png) [@rapropos](https://forum.ionicframework.com/u/rapropos)\
**Post date:** [August 10, 2020, 5:52pm UTC](https://forum.ionicframework.com/t/loading-controller-await-problem/194089/6 "2020-08-10T17:52:55Z")

</div>

> [@enfix](#):
>
> I wanted to understand how it works

[Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)’s MDN on the subject.

> [@enfix](#):
>
> why it doesn’t work with async

Because you never `await` the call to `this.presentLoading()`.

> [@Daveshirman](#):
>
> Maybe you should edit your comment to include the alternative code snippet you are suggesting enfix should use?

Here’s how I would write this.

```auto
export class HomePage {
  result = "pending";
  winner$: Observable<string> = of("won").pipe(delay(2000));
  loser$: Observable<string> = throwError("you lose");

  constructor(private loaderer: LoadingController, private alerter: AlertController) {
  }

  doit(feeder: Observable<string>): void {
    this.loaderer.create({message: "loading..."})
      .then(lc => lc.present())
      .then(() => {
        feeder.pipe(finalize(() => this.loaderer.dismiss()))
          .subscribe(r => this.result = r, err => this.notifyError(err));
      });
  }

  notifyError(msg: string): void {
    this.result = "failed";
    this.alerter.create({message: msg}).then(dlog => dlog.present());
  }

  goWin(): void {
    this.doit(this.winner$);
  }

  goLose(): void {
    this.doit(this.loser$);
  }
}

```

```auto
<ion-content>
  <ion-item>
    <ion-label>{{result}}</ion-label>
  </ion-item>
  <ion-button (click)="goWin()">win</ion-button>
  <ion-button (click)="goLose()">lose</ion-button>
</ion-content>

```

Press the “win” button, you should see the loading indicator appear, sit there for a couple of seconds, disappear, and the result should be displayed as “won”. Press the “lose” button, the loading indicator should appear, disappear, be replaced by an alert, and the result should be displayed as “failed”.

Things to note:

- no `async` / `await`
- no `any`
- no storing transient objects in controller properties (your `loading`). it becomes very difficult glancing at the code to know who is responsible for managing this object’s lifecycle, and if you mess that up, you end up with resource leaks or triggering double-dispose bugs
- `finalize` operator allows centralizing instead of duplicating tear-down code
- explicit return type declarations for all methods
