Search code examples
angulartypescriptionic-frameworkasync-awaitlifecycle

Making lifecycle hooks asynchronous in typescript (Angular, Ionic)


I am curious about using typescript feature, which is async/await, with lifecycle hooks.

The feature is really convenient but is it okay to make lifecycle hooks async?

I've tested this approach many times and it works as intended but I couldn't find any reliable answer is it good practice and I'm afraid it may be not.

for illustration:

Angular:

async ngOnInit() {
  await someAsyncFunction();
}

Ionic:

async ionViewWillEnter() {
  await someAsyncFunction();
}

Solution

  • I don't know about "relatively new" - it's been there since 2.1.

    The feature is really convenient but is it okay to make lifecycle hooks async?

    There are several articles out there that are doing what you're doing (just google async await ngOnInit). Nothing to suggest it's not ok doing it with angular. Don't know about ionic.

    but I couldn't find any reliable answer is it good practice and I'm afraid that it may be not.

    The problem with good practices is that they're opinionated. Personally, I think it makes the code much more readable. You can check out https://medium.com/@benlesh/async-await-it-s-good-and-bad-15cf121ade40 to see another opinion, and a more detailed analysis.