在打字稿中使生命周期挂钩异步(Angular,离子)
Making lifecycle hooks asynchronous in typescript (Angular, Ionic)
我很好奇使用带生命周期挂钩的 typescript 功能 async/await。
这个功能确实很方便,但是可以让生命周期钩子异步吗?
我已经多次测试这种方法并且它按预期工作,但我找不到任何可靠的答案是不是很好的做法,恐怕它可能不是。
举例说明:
Angular:
async ngOnInit() {
await someAsyncFunction();
}
离子:
async ionViewWillEnter() {
await someAsyncFunction();
}
我不知道 "relatively new" - 它从 2.1 开始就有了。
The feature is really convenient but is it okay to make lifecycle
hooks async?
有几篇文章正在做您正在做的事情(只是 google async await ngOnInit)。没有任何迹象表明用 angular 做这件事不好。不知道离子。
but I couldn't find any reliable answer is it good practice and I'm
afraid that it may be not.
好的做法的问题在于它们固执己见。就个人而言,我认为它使代码更具可读性。您可以查看 https://medium.com/@benlesh/async-await-it-s-good-and-bad-15cf121ade40 以查看其他意见和更详细的分析。
根据我的经验,使用 async/await 和 Angular 生命周期挂钩没有问题。据我所知,它也不是一种糟糕的编程习惯。我曾经使用 async 实现我的生命周期方法,后来没有任何问题。
如果您有疑问,也可以查看此线程以获取更多信息:https://github.com/angular/angular/issues/17420
我很好奇使用带生命周期挂钩的 typescript 功能 async/await。
这个功能确实很方便,但是可以让生命周期钩子异步吗?
我已经多次测试这种方法并且它按预期工作,但我找不到任何可靠的答案是不是很好的做法,恐怕它可能不是。
举例说明:
Angular:
async ngOnInit() {
await someAsyncFunction();
}
离子:
async ionViewWillEnter() {
await someAsyncFunction();
}
我不知道 "relatively new" - 它从 2.1 开始就有了。
The feature is really convenient but is it okay to make lifecycle hooks async?
有几篇文章正在做您正在做的事情(只是 google async await ngOnInit)。没有任何迹象表明用 angular 做这件事不好。不知道离子。
but I couldn't find any reliable answer is it good practice and I'm afraid that it may be not.
好的做法的问题在于它们固执己见。就个人而言,我认为它使代码更具可读性。您可以查看 https://medium.com/@benlesh/async-await-it-s-good-and-bad-15cf121ade40 以查看其他意见和更详细的分析。
根据我的经验,使用 async/await 和 Angular 生命周期挂钩没有问题。据我所知,它也不是一种糟糕的编程习惯。我曾经使用 async 实现我的生命周期方法,后来没有任何问题。
如果您有疑问,也可以查看此线程以获取更多信息:https://github.com/angular/angular/issues/17420