stick-to-this
Version:
A ttiny utility to greatly reduce verbosity in using Promises.
63 lines (54 loc) • 2.27 kB
Markdown
## What is it?
Creates a proxy function (from a an object's member function) with access to the parent object's data not otherwise available to it because the original _this_ binding was lost or overridden when called. For example, that happens when the function is called in a _bluebird_ promise chain and is preceded by a _.bind_ instruction.
## Why use it?
Bluebird's _.bind_ method makes it possible for multiple steps in a promise chain to collaborate on context, where they utilize resources from the context object. For example:
```js
var context = {/*...*/}
return Promise.bind(context)
.then(fn1)
.then(fn2)
.then(fn2);
```
Unfortunately, this will break a function is a member of an object that depends on access to its original _this_. The below will not work:
```js
class Transform {
constructor(_prefix, _suffix){
this.prefix = _prefix;
this.suffix = _suffix;
}
prepend(){
this.message = this.prefix + this.message;
}
append(context){
this.message += this.suffix;
}
}
var t = new Transform('hello ', '!');
var context {message: 'george'};
return Promise.bind(context)
.then(t.prepend) //breaks: this.prefix will not be there
.then(t.append) //breaks: this.suffix will not be there
```
If somehow both _context_ and _t_ are available inside then the plan will work, and _bind-to-this_ helps make that happen:
```js
var stick = require('stick-to-this');
prepend(context){
this.message = _this.prefix + this.message;
}
append(context){
this.message += _this.suffix;
}
class Transform {
constructor(_prefix, _suffix){
this.prefix = _prefix;
this.suffix = _suffix;
this.prepend = stick(this, prepend);
this.append = stick(this, append);
}
var t = new Transform('hello ', '!');
var context {message: 'george'};
return Promise.bind(context)
.then(t.prepend)
.then(t.append)
```
In a for useful setting, the context object may be a container that provides access to _request_ and _response_ objects.