ES6课程中的承诺

时间:2016-02-11 14:47:06

标签: 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.

1 个答案:

答案 0 :(得分:12)

这就是箭头功能的用途:

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