I'm currently writing up my promise chains and am coming across an odd issue with Bluebird. Using babel-node and ES6, I'm trying to create a promise chain that doesn't require me having to do .then(function() { return foo(); });
but instead .then(foo)
. The issue is the data in my constructor gets removed when the function is called in the shorter form.
Here's a quick example.
import Promise from 'bluebird';
class TestClass {
constructor() {
this.my_var = 'Hello!';
}
startOne() {
var self = this;
return this.wait()
.then(function() { return self.myself(); });
}
startTwo() {
return this.wait().then(this.myself);
}
wait() {
return Promise.delay(1000);
}
myself() {
if (!this) return console.log('I\'m not feeling like myself today...');
console.log(this);
}
}
var foo = new TestClass();
foo.startOne();
foo.startTwo();
When foo.startOne()
is called, which is using the longer version of the chain, it properly returns {my_var: 'Hello'}
. However when foo.startTwo()
is called, this
is undefined
.
Why is that? How am I writing my chain incorrectly that this
becomes undefined? Or is it really just supposed to be written like the first example?
Thanks.