1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Basing on my experience there are no issues with using async/await with Angular life cycle hooks. As far as I know it is also not known for being a bad programming practice. I used to implement my life cycle methods with async without any problems later.

If you have doubts you can also check this thread for more information: https://github.com/angular/angular/issues/17420

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.