javascript - 避免在 javascript 中加载事件链
问题描述
我的代码中有一个问题,其中许多实体具有异步加载过程,并且在这些完成之前无法使用。存在这些依赖关系的链。所以A->B->C
A需要B需要C。
我写过类似的代码
class B{
constructor(callback){
this.loaded=false
this.load(callback)
}
load(callback){
...do stuff
this.loaded=true
callback()
}
}
class A{
constructor(){
this.loaded=false
this.b=new B(()=>{this.loaded=true})
}
}
这似乎真的很糟糕。任何人都可以提出更好的解决方案吗?
解决方案
通常,直接在构造函数中执行异步任务是一种不好的做法(如此处所述)。考虑到这一点,您可以遵循 VLAZ 的建议并开始使用 Promise。
然后你会有这样的东西:
class B {
constructor() {
this.loaded = false
}
load() {
return new Promise((resolve => {
this.loaded = true;
// do stuff
return resolve()
}))
}
}
class A {
constructor() {
this.loaded = false
}
load() {
return new Promise(resolve => {
this.b = new B()
this.loaded = true
return resolve(this.b)
})
}
}
// Use it like this
const a = new A()
a.load()
.then(b => b.load())
.then(/* and so on */)
推荐阅读
- python - pandas.datetime64 值的线性拟合?
- javascript - 仅使用 URL 在表单数据中附加文件
- bootstrap-4 - Bootstrap 4 列排序用例
- python - 从两个列表创建目录
- javascript - 在 Node JS 中链接请求和事件数据
- php - 流明 - handler.php 不反映更新
- laravel - 带有参数的 http POST 到 /session 引发的 curl 错误:Facebook\WebDriver\Exception
- f# - 错误 FS0193:类型约束不匹配
- python - LUNA16 切片注释
- opencv - OpenCV:特征匹配+单应性帮助调整结果