我刚刚开始使用Promise尝试清除一些“回调地狱”。
我决定尝试使用bluebird,并在浏览器中运行它,但立即遇到了范围界定问题。
有没有办法在新的Promise中设置thisArg?下面的示例显示了Promise解析器中的'this'值设置为浏览器窗口,但是我希望将其设置为周围的范围,这样我就可以轻松访问成员变量。
我注意到有一个.bind()方法,但它只作用于'then()'方法的作用域,而不是promise的作用域。我也意识到我可以在promise和use闭包之前使用'var me = this',但是我想尽可能避免使用它。
function MyObject() {
this.value = 7;
}
MyObject.prototype.getValue = function () {
return new Promise(function (resolve) {
// some request/processing that takes a long time
var result = Ajax.request(...);
resolve({
value: this.value,
result: result
});
// 'this' is set to window instead of the instance,
// resulting in this.value as undefined
});
}
var obj = new MyObject();
obj.getValue().then(function (value) {
console.log(value); // preferably outputs 7
})
不,那里没有。您当然可以使用默认方法,但是您不必这样做。
在进行繁重的处理并异步获取值时,您希望获得对值的承诺。您无需将结果值设置为原始实例的属性。
MyObject.prototype.getValue = function () {
return new Promise(function(resolve) {
// lots of processing to make a `value`
resolve(value); // no `this` at all!
});
};
如果要同步获取在.value
实例上设置的,则不需要Promise
构造函数。只需使用Promise.resolve
对现有价值的承诺即可:
MyObject.prototype.getValue = function () {
// TODO: lots of processing
return Promise.resolve(this.value);
};
或者,就您而言,甚至Promise.method
:
// TODO: lots of processing
MyObject.prototype.getValue = Promise.method(function () {
return this.value;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句