Skip to content

Instantly share code, notes, and snippets.

@kerihenare
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerihenare/8168686dd7bb6b427218 to your computer and use it in GitHub Desktop.
Save kerihenare/8168686dd7bb6b427218 to your computer and use it in GitHub Desktop.
How to Scope
/**
* Reference "this"
*/
var self = this;
self.someOtherMethod = function (result) {
var self = this;
return new Promise(function (resolve, reject) {
self.callbackMethod(result, function (error, result) {
if (error) {
return reject(error);
}
resolve(result);
});
});
}
someMethod()
.then(function (result) {
return self.someOtherMethod(result);
});
/**
* Bind "this"
*/
this.someOtherMethod = function (result) {
return new Promise(function (resolve, reject) {
this.callbackMethod(result, function (error, result) {
if (error) {
return reject(error);
}
resolve(result);
});
}.bind(this));
}
someMethod()
.then(function (result) {
return this.someOtherMethod(result);
}.bind(this));
/**
* Arrow functions (doesn't work without transpiling)
*/
this.someOtherMethod = (result) => {
new Promise((resolve, reject) => {
this.callbackMethod(result, (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
});
}
someMethod()
.then((result) => {
return this.someOtherMethod(result);
});
@kerihenare
Copy link
Author

I know that technically I could just use I could just use .then(this.someOtherMethod); and the last bit could just be .then((result) => this.someOtherMethod(result)); but I was trying to keep the comparison more direct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment