ES6课程中的承诺

Gro*_*Com 5 javascript promise ecmascript-6 bluebird

我正在尝试编写一个具有返回promises和promise链的方法的类.此尝试从do_that()返回错误

我理解使用'this'的问题,这就是为什么我使用self = this kludge,但我仍然会收到错误.

TypeError:无法读取未定义的属性"name".

除了这个问题,我该如何解决这个问题,还有更简洁的方法吗?

var Promise = require('bluebird');

    class myClass {

        constructor(name, pipeline) {
            this.name = name;
        }

        do_this() {
            var self = this;    // <-- yuck. Do I need this?
            return new Promise(function(resolve, reject) {
                setTimeout(function () { console.log("did this " + self.name);  resolve(self);  }, 1000);
            })
        }

        do_that() {
            var self = this;    // <-- yuck
            return new Promise(function(resolve, reject) {
                setTimeout(function () { console.log("did that " + self.name);  resolve(self);  }, 1000);
            })
        }

        do_both() {
            return this.do_this().then(this.do_that);
        }

    }

    new myClass("myobj").do_both();  // <-- TypeError: Cannot read property 'name' of undefined.
Run Code Online (Sandbox Code Playgroud)

Mat*_*ics 14

这就是Arrow Functions的用途:

 do_that() {
        return new Promise((resolve, reject) => {
            setTimeout(() => { console.log("did that " + this.name);  resolve(this);  }, 1000);
        })
    }
Run Code Online (Sandbox Code Playgroud)

  • 这部分回答了这个问题.另一个问题是`do_both`传递`this.do_that`后来被称为无界.所以要么'返回this.do_this().然后(this.do_that.bind(this));`或`返回this.do_this().然后(x => this.do_that(x));`在那种情况下 (7认同)
  • @GroovyDotCom你可以在构造函数中绑定你的方法:`this.do_that = this.do_that.bind(this);` - 那么你就不必在代码中的任何其他地方绑定它.这种模式很常见,实用程序库包含[`bindAll`](https://lodash.com/docs#bindAll)等函数,以使其更容易. (6认同)
  • @GroovyDotCom 如果您的主要目标是“漂亮”的代码,那么 JavaScript 对您来说可能是错误的语言。 (2认同)
  • @GroovyDotCom它没有引入类,它为现有的构造函数模式引入了`class`关键字作为糖.引擎盖下没有任何新功能. (2认同)