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.
This is what Arrow Functions are for:
do_that() {
return new Promise((resolve, reject) => {
setTimeout(() => { console.log("did that " + this.name); resolve(this); }, 1000);
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With