Promise中处理上下文的正确方式

Correct way of handling context in Promise

本文关键字:方式 上下文 处理 Promise      更新时间:2023-09-26

有一些关于这个主题的帖子,但在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) {
  ......
 }
}
}
})

现在,我的问题如下:

  1. 请参阅上面prepareForProcessing函数中的注释。当从promise的"then"方法调用时,"this"变量在方法内部指的是什么?如果我转储"this"对象,它似乎指的是某个全局节点/成员cli对象,而不是这个模块
  2. 如何在方法中检索/访问上述属性?一个明显的方法是将选项作为参数传递,但不确定这是否是正确的方法。如果你看一下这里的代码(第34行),每个"then"调用都会传递选项。但是,这是否违背了OOP的原则,即拥有可以重用的类/实例级变量?我对JS还比较陌生,完全不理解基于"对象"的模型,所以如果这听起来像是一个愚蠢的问题,请原谅我

我将感谢任何帮助&指导非常感谢。

您需要使用Function.prototype.bind:

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