2015-12-24 58 views
0

該主題有幾個帖子,但找不到解釋Promise中上下文概念的帖子。讓我們從一些代碼開始(這是從Ember.js模塊抽取並簡化,但可能是支持的承諾任何JS代碼):在Promise中處理上下文的正確方法

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'的方法被調用時,'this'變量在方法內引用了什麼?如果我轉儲'this'對象,它似乎是指一些全局節點/ ember cli對象而不是這個模塊。
  2. 如何在方法中檢索/訪問上述屬性?一種顯而易見的方式是將選項作爲參數傳遞,但不確定這是否正確。如果您查看代碼here(行號34),則會爲每個「接下來的」調用傳遞選項。但是,這是否違背了OOP可以重用的類/實例級變量的原則?我對JS比較陌生,完全不瞭解基於「對象」的模型,所以請原諒我,如果這聽起來像一個愚蠢的問題。

我將不勝感激任何幫助&指導。非常感謝你。

+0

我不明白爲什麼'this'不會是你'prepareProcessing'會發生什麼,因爲你永遠只通過'this'稱之爲:'這.prepareForProcessing(...)'。 –

回答

0

您需要使用Function.prototype.bind

this.prepareForProcessing(whatToProcess).then(this.process.bind(this)).then(this.postProcess.bind(this)); 
相關問題