【发布时间】:2014-11-06 18:38:41
【问题描述】:
我刚刚开始使用 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
})
【问题讨论】:
标签: javascript promise bluebird