在Promise中处理上下文的正确方法

时间:2015-12-24 17:37:01

标签: javascript node.js ember-cli ember-cli-addons rsvp-promise

关于这个主题有一些帖子,但在Promises中找不到解释语境概念的帖子。让我们从一些代码开始(这取自Ember.js模块并简化,但可以是任何支持promises的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) {
  ......
 }

}

}
})

现在,我的问题如下:

  1. 请参阅上面的prepareForProcessing函数内的注释。当从承诺的'then'方法调用时,'this'变量在方法内引用了什么?如果我转储'this'对象,它似乎引用了一些全局node / ember cli对象而不是这个模块。
  2. 如何在方法中检索/访问上述属性?一种显而易见的方法是将选项作为参数传递,但不确定这是否是正确的方法。如果你查看代码here(第34行),那么每个'then'调用都会传递选项。但是,这是否违背了OOP原则,即具有可以重用的类/实例级变量?我对JS比较陌生,并且完全不了解基于'对象'的模型,所以如果这听起来像是一个愚蠢的问题,请原谅我。
  3. 我很感激任何帮助&指导。非常感谢你。

1 个答案:

答案 0 :(得分:0)

您需要使用Function.prototype.bind

this.prepareForProcessing(whatToProcess).then(this.process.bind(this)).then(this.postProcess.bind(this));