0

I want to write code like this using ES7 async callbacks.

class Foo {

  bar(app) {

    // const that = this
    app.on('something', async function() {
      await this.baz() // `this` is `app`. I want it to be the instance of Foo (`that`)
    }

  }

  async baz() {
    console.log('baz')
  }

}

In ES6 we can use anon funcs, but I can't use await inside. I could use promises, but I want the simplicity of await.

app.on('something', () => {
  this.baz()
})

We could use a separate method for the callback. But this is verbose.

class Foo {

  bar(app) {
    app.on('something', this.onSomething)
  }

  async onSomething() {
    await this.baz() // `this` is `app`. I want it to be the instance of Foo (`that`)
  }

  async baz() {
    console.log('baz')
  }

}

So what is the best way given my constraints?

vaughan
  • 6,982
  • 6
  • 47
  • 63

1 Answers1

1

Missed the obvious - I thought I had read something earlier that it was not possible to use anon funcs with async.

app.on('live-app:start', async () => { this })
vaughan
  • 6,982
  • 6
  • 47
  • 63