Promises in ES6 Classes

I am trying to write a class that has methods that return promises and immobilized chains. This attempt returns an error from do_that ()

I understand the problem using 'this', so I used self = this kludge, but I still get the error message.

TypeError: Unable to read the 'name' property from undefined.

In addition to the question, how can 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.
+4
source share
1 answer

These are arrow functions for:

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

Source: https://habr.com/ru/post/1628327/


All Articles