0

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.

Dustin
  • 5,457
  • 18
  • 53
  • 82
  • 1
    This is a basic JS issue, if you review http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work, example #3 in the first answer demonstrates your issue. You are doing `var tmp = this.myself; tmp()` which makes `this === undefined`. Since you are using ES6, use an arrow function, e.g. `.then(() => this.myself())` Issues like this are asked so often I'm not sure what to dup this into. – loganfsmyth Sep 02 '15 at 20:50
  • @loganfsmyth: We've got one specifically for bluebird promises :-) – Bergi Sep 03 '15 at 12:38

1 Answers1

0

This is a regular Javascript problem with passing a function reference (nothing specific to do with promises).

When you pass this.myself as a function argument, all that gets actually passed is a reference to the myself function and the binding to the this object is lost so when the function is called, the this pointer will be wrong and won't point to your object's instance data. There are numerous ways to work around this. This is a generic Javascript issue with passing callback functions that are methods. There are a number of ways to work around this.

You can use .bind() to keep the this reference property attached like this:

 return this.wait().then(this.myself.bind(this));
jfriend00
  • 580,699
  • 78
  • 809
  • 825