【问题标题】:Asynchronous functions in constructor构造函数中的异步函数
【发布时间】:2017-04-14 12:22:07
【问题描述】:

我正在尝试在构造函数中使用异步调用导出一个类:

my.js:

module.exports = class My extends Emitter {
  constructor () {
    super()
    this.db = Object.create(db)
    this.db.init(cfg)
  }
}

db.js:

module.exports = {
  async init (cfg) {
    nano = await auth(cfg.user, cfg.pass)
    db = nano.use(cfg.db)
  },
  async get (id) {
    ...
  }

let my = new My() 之后,my.db 仍然是空的。如何等待 init() 完成?

【问题讨论】:

    标签: javascript async-await ecmascript-2017 koa2


    【解决方案1】:

    如果你这样做

    module.exports = class My extends Emitter {
      constructor () {
        super()
        this.db = Object.create(db)
        this.waitForMe = this.db.init(cfg)
      }
    }
    let my = new My();
    

    知道 async/await 只是 Promises 的糖,你可以像这样等待:

    my.waitForMe.then(function() {
    });
    

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 2013-12-27
      • 2014-10-28
      • 2018-06-26
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 2020-07-28
      • 2018-09-16
      相关资源
      最近更新 更多