将ES7异步回调绑定到父作用域上下文的最简洁的方法是什么?

What is the most concise way to bind an ES7 async callback to its parent scope context

本文关键字:简洁 方法 是什么 上下文 作用域 异步 ES7 回调 绑定      更新时间:2023-09-26

我想用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中我们可以使用匿名函数,但是我不能在里面使用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')
  }
}

那么在我的约束条件下,什么是最好的方法?

错过了显而易见的-我以为我之前读过一些东西,认为不可能在async中使用匿名函数。

app.on('live-app:start', async () => { this })