0

I'm trying to export a class with an asynchronous call in the constructor:

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) {
    ...
  }

After let my = new My(), my.db is still empty. How do I wait for init() to be completed?

Patrick
  • 7,903
  • 11
  • 52
  • 87

1 Answers1

1

If you do something like

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

Knowing that async/await is just sugar for Promises, you can then wait like:

my.waitForMe.then(function() {
});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87