JKE
JKE

Reputation: 35

Chained Promises (Q deferred) with Object / Prototype

I have a simple Javascript (Node) object, which has a function that sets a property on the object and returns a promise.

Note, for this example I've removed the actual async call that needs to be deferred, as it doesn't effect the outcome.

var q = require("Q");

var Foo = function(){
  this.bar = false;
  return this;
};

Foo.prototype.set = function(){
  var d = q.defer();
  this.bar = true; 
  d.resolve();
  return d.promise;
};

Foo.prototype.check = function(){
  var d = q.defer();
  console.log(this.bar);
  d.resolve();
  return d.promise;
};

When the above is called in a promise-defeating way like below, this.bar is true (as expected).

var foo = new Foo();
foo.set().then(function(){
  foo.check();
});

However, when it's called in a chain, it's undefined:

foo.set().then(foo.check);

I'm curious to understand what's causing this. My best guess is a closure issue with the way that my object's methods are chained together.

In most cases, I'd pass the value to resolve/reject and go from there. In this case, I want to run some data through a series of sequential functions (some requiring deferment). Rather than passing the output to each function in the chain, I want to store and update the data in the object itself.

Any clarity would be much appreciated!

Upvotes: 2

Views: 268

Answers (1)

Eugene Glova
Eugene Glova

Reputation: 1553

The problem you calls callback without context and this is just global object

As a solution you need to bind context like this

foo.set().then(foo.check.bind(foo));

Upvotes: 3

Related Questions