Last active
August 29, 2015 14:24
-
-
Save kerihenare/8168686dd7bb6b427218 to your computer and use it in GitHub Desktop.
How to Scope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.