小编rdb*_*max的帖子

如何在javascript ES6类中链接异步方法

我想从类中链接方法.我有同步方法的问题,但我不知道如何使用异步方法.

例如,这个类:

class Example {

  constructor() {
    this.val = 0
  }

  async () {
    setTimeout(() => {
      this.val += 1
      return this
    }, 5000)
  }

  sync () {
    this.val += 1
    return this
  }

  check () {
    console.log('checker', this.val)
    return this
  }

}
Run Code Online (Sandbox Code Playgroud)

这有效:

new Example().sync().check()
> 1
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

new Example().async().check()
> TypeError: Cannot read property 'check' of undefined
Run Code Online (Sandbox Code Playgroud)

PS我想要链接,而不是地狱回调.

javascript class chaining node.js ecmascript-6

2
推荐指数
2
解决办法
9072
查看次数

标签 统计

chaining ×1

class ×1

ecmascript-6 ×1

javascript ×1

node.js ×1