Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promises in ES6 Classes [duplicate]

I'm trying to write a class that has methods that return promises and promise chains. This attempt returns error from do_that()

I understand the problem with using 'this' which is why I used the self=this kludge, but I still get an error.

TypeError: Cannot read property 'name' of undefined.

In addition to the question, how do I fix this, is there a cleaner way to do this?

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.
like image 585
GroovyDotCom Avatar asked Feb 11 '16 14:02

GroovyDotCom


1 Answers

This is what Arrow Functions are for:

 do_that() {
        return new Promise((resolve, reject) => {
            setTimeout(() => { console.log("did that " + this.name);  resolve(this);  }, 1000);
        })
    }
like image 70
Mathletics Avatar answered Oct 21 '22 14:10

Mathletics