0

ES7 非同期コールバックを使用して、このようなコードを書きたいと思います。

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')
  }

}

ES6 では anon 関数を使用できますが、内部で await を使用することはできません。promise を使用することもできますが、await の単純さが必要です。

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

コールバックには別のメソッドを使用できます。しかし、これは冗長です。

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')
  }

}

私の制約を考えると、最善の方法は何ですか?

4

1 に答える 1

1

明らかなことを見逃しました-非同期でアノン関数を使用することはできないということを以前に読んだことがあると思いました。

app.on('live-app:start', async () => { this })
于 2015-07-26T14:26:11.540 に答える