首页 > 解决方案 > 避免在 javascript 中加载事件链

问题描述

我的代码中有一个问题,其中许多实体具有异步加载过程,并且在这些完成之前无法使用。存在这些依赖关系的链。所以A->B->CA需要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})
  }
}

这似乎真的很糟糕。任何人都可以提出更好的解决方案吗?

标签: javascript

解决方案


通常,直接在构造函数中执行异步任务是一种不好的做法(如此所述)。考虑到这一点,您可以遵循 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 */)

推荐阅读