tildeio/rsvp.js — pull request #18 by richtr (2012-10-23 19:03:37+00:00)
Title:  Custom 'this' keyword assignment in .then() arguments

Just wanted to get your thoughts on adding a way to set the this keyword within then function arguments.

My proposal is to allow an optional argument when creating a new RSVP.Promise:

var promise = new RSVP.Promise( binding );

where binding is set as the value for the this keyword in any subsequent promise.then function argument. This assignment also cascades down through any chaining of then calls.

So if I create a Promise-returning class object such as the following:

var Foo = function() {
this.bar = function() {
var promise = new RSVP.Promise( this );
// ...
return promise;
};
this.baz = "baz";
};

...and then I call the following code:

var foo = new Foo();
var a = foo.bar().then(function(result) {
console.log( this.baz );
}, function(error) {
console.log( this.baz );
});

...both console.log functions will display the result "baz" because this has been set as an object of type Foo.

FWIW, I ran this patch against [promise-tests](https://github.com/domenic/promise-tests) with all optional test sets included with a 100% pass result (40/40).

Interested in further discussion here if necessary and thanks for sharing this lib.