Promise中处理上下文的正确方式
Correct way of handling context in Promise
有一些关于这个主题的帖子,但在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) {
......
}
}
}
})
现在,我的问题如下:
- 请参阅上面prepareForProcessing函数中的注释。当从promise的"then"方法调用时,"this"变量在方法内部指的是什么?如果我转储"this"对象,它似乎指的是某个全局节点/成员cli对象,而不是这个模块
- 如何在方法中检索/访问上述属性?一个明显的方法是将选项作为参数传递,但不确定这是否是正确的方法。如果你看一下这里的代码(第34行),每个"then"调用都会传递选项。但是,这是否违背了OOP的原则,即拥有可以重用的类/实例级变量?我对JS还比较陌生,完全不理解基于"对象"的模型,所以如果这听起来像是一个愚蠢的问题,请原谅我
我将感谢任何帮助&指导非常感谢。
您需要使用Function.prototype.bind
:
this.prepareForProcessing(whatToProcess).then(this.process.bind(this)).then(this.postProcess.bind(this));
相关文章:
- 将函数的上下文应用于javascript变量
- 为什么这在IE中的工作方式与在Firefox中不同
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在localhost Dev Box上测试JSONP请求的最佳方式
- 使用JQuery的动态上下文菜单
- 使用javascript存储变量的最安全方式
- 以可优化的方式使用requirejs加载模板
- 在Highcharts中,我们可以通过任何方式在渲染图表之前获得plotWidth和plotHeight
- 任何方式使AJAX调用Gmail API,而无需通过JS库
- 如何访问UIWebView'的子窗口上下文
- 为react组件传递道具的最佳方式
- 让Webpack管理Quirky AMD定义的最佳方式
- 在承诺链中处理早期回报的最佳方式
- 如何“;过滤器”;或者以其他方式重构该数据
- Promise中处理上下文的正确方式
- 在setTimeout上使用.apply或.call——如何以跨平台的方式获得这个上下文
- 事件——为什么上下文以两种不同的方式存储
- 设置上下文的不同方式