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

标签 javascript node.js class ecmascript-6 chaining

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

例如这个类:

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
  }

}

这个有效:

new Example().sync().check()
> 1

但这行不通:

new Example().async().check()
> TypeError: Cannot read property 'check' of undefined

附言我想要链接,而不是 hell 回调。

最佳答案

我希望您在超时到期后调用 check()。问题是 fork ,您无法立即返回可用的东西。

你可以传入 check() 作为回调:

class Example {

  constructor() {
    this.val = 0
  }

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

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

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

}

// execution
var ex = new Example();
ex.async(ex.check)

……或者一个 promise

class Example {

  constructor() {
    this.val = 0
  }

  async (callback) {
    var deferred = Q.defer()
    setTimeout(() => {
      this.val += 1
      deferred.resolve();
    }, 5000)
    return deferred.promise;
  }

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

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

}

// execution
var ex = new Example()
ex.async().then(() => ex.check())

...或者你可以使用 ES6 生成器

关于javascript - 如何在 JavaScript ES6 类中链接异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32655656/

相关文章:

JavaScript IE 问题

javascript - jQuery - img src 中的变量返回未定义

javascript - 表达 js,mongodb : “ReferenceError: db is not defined” when calling a function

class - Smalltalk/Squeak消息处理方法

c++ - 缺少类模板 "Complex"的参数列表

javascript - 无论如何,是否可以将 html 元素从一个客户端传输到另一个客户端,同时保留每个输入的值,例如在文本框中?

javascript - FirebaseError : Expected first argument to collection() to be a CollectionReference, a DocumentReference 或 FirebaseFirestore,正在迁移到 v9 firebase

node.js - 为什么 cron 不执行我的 node.js 脚本?

javascript - 面向个人用户的带有 Node.js 和 Socket.io 的 Pubsub

class - Smalltalk 中的 self 和 super