我刚刚开始使用 promises 来尝试清理一些“回调 hell ”。
我决定尝试使用 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
})
最佳答案
不,没有。你当然可以use the default approaches ,但您不需要这样做。
当进行繁重的处理并异步取回值时,您希望对值 有一个 promise 。您不需要将结果值设置为原始实例的属性。
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
对现有值(value)作出 promise :
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;
});
关于javascript - Bluebird promise 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25810728/