[英]Correct way of handling context in Promise
There are a few posts on the topic, but couldn't find one that explains the concept of context in Promises. 关于该主题的文章很少,但是找不到一个可以解释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):
让我们从一些代码开始(这是从Ember.js模块中提取并简化的,但是可以是任何支持promise的JS代码):
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: 现在,我的问题如下:
I would appreciate any help & guidance. 我将不胜感激任何帮助和指导。 Thank you so very much.
非常感谢你。
您需要使用Function.prototype.bind
:
this.prepareForProcessing(whatToProcess).then(this.process.bind(this)).then(this.postProcess.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.