There are a few posts on the topic, but couldn't find one that explains the concept of context in Promises. Lets start with some code (this is taken from an Ember.js module and simplified, but could be any JS code that supports promises):
module.exports = CoreObject.extend({
init: function(pluginOptions, parentObject) {
//These are the properties that I want to access in methods below.
this.parentObject = parentObject;
this.propertyA = pluginOptions.propertyA;
this.propertyB = pluginOptions.propertyB;
},
startProcessing: function(whatToProcess) {
/* The following line does not work which is okay
return this.prepareForProcessing(whatToProcess).then(process).then(postProcess(processedData, this); */
//This line does work, but parameters to then don't work. The result of prepareForProcessing is not passed to process and so on.
return this.prepareForProcessing(whatToProcess).then(this.process).then(this.postProcess);
},
prepareForProcessing: function(whatToProcess) {
//this does not work as 'this' is set to a different context
//What does 'this' refer to here?
//How do I access propertyA, propertyB defined at the beginning of this object?
if(this.propertyA) {
....
}
process: function(preparedData) {
//this does not work either
if(this.propertyB) {
.....
}
}
postProces: function(processedData, options) {
//This should work for obvious reasons but is the best way?
if( options.propertyA) {
......
}
}
}
})
Now, my questions are as follows:
- Refer to comments inside prepareForProcessing function above. What does the 'this' variable refer to inside the method, when called from a 'then' method of a promise? If I dump the 'this' object, it seems like it refers to some global node/ember cli object and not this module.
- How do I retrieve/access the above mentioned properties in the method? One obvious way would be to pass option as arguments, but not sure if that is the right way.If you look at the code here (line number 34), the options are being passed around for each 'then' call. But then does this not go against OOP principles of having class/instance level variables that can be reused? I'm relatively new to JS and don't understand the 'Object' based model, completely, so please forgive me if this sounded like a stupid question.
I would appreciate any help & guidance. Thank you so very much.
You need to use
Function.prototype.bind
: