从 promise 内部在外部作用域中设置变量



我正在尝试更新 promise 函数范围之外的值,但很难弄清楚如何做到这一点。我认为设置 self = 这将纠正此处建议的范围问题,但 self.value 在承诺范围之外仍然是 0。相关代码如下。

window.App = {
foo: function() {
var self = this;
self.value = 0;
self.func1 = function() {
func2().then(function(result1) {
return func3(result1);
}).then(function(result2) {
self.value = result2;
})
}
},
bar: function() {
var fooObject = new this.foo();
fooObject.func1();
},
baz: function() {
var fooObject = new this.foo();
func4(fooObject.value);
}
}

我怎样才能在承诺中设置自我价值的价值?我想稍后通过 foo.value 在应用程序内的代码中访问此值。

下面是一个我试图像你的代码一样构建的承诺示例:

window.App = {
foo: function() {
var self = this;
self.value = 0;
this.func2 = function(){
return 1;
}
self.func1 = function(){
return new Promise((resolve, reject) => {
console.log("before execute value: " + self.value);
resolve(self.func2());
}).then(function(result) {
self.value = result;
console.log("promise then value: " + self.value);
});
}
}   
}
var o = new window.App.foo();
var promise = o.func1();
console.log("outside value: "+o.value);
promise.then(function(){
console.log("outside promise then value: "+o.value);
})

最新更新