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?

1 Answer 1

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() {
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.