我目前正在与 promise 作斗争,我认为我的概念有点错误。基本上我想做的是编写一个小模板处理程序。
它有一个 load() 方法,该方法加载模板并将其存储到属性中,并且它将是可链接的。我想要链接它的方法是 attachTo()
,它将我之前加载的模板附加到 DOM 元素。
由于模板是异步加载的,我尝试使用 Promise。但看起来 Promise 上的 done()
方法是在异步调用完成之前立即触发的。
我这样调用它:
tpl.load('stuff.html').attachTo($('.someElement'));
我希望它的行为是,每当我调用 attachTo()
时,它都会等待我之前调用的 load() 方法来完成它的异步工作,然后触发中提供的回调done
方法。
这是处理程序的相关部分
var tpl = {
...
template: null,
promise: null,
load: function(template) {
this.promise = $.get(this.templateUrl + template, function(response){
this.template = response;
console.log(this.template);
//Outputs the desired value
});
return this;
},
attachTo: function(el) {
var self = this;
$.when(this.promise).done(function(){
//outputs null but should output the
//value that has been set in my async call
console.log(self.template);
});
}
..
}
tpl.load('stuff.html').attachTo($('.someElement'));
最佳答案
虽然您自己已经发现了问题,但建议的解决方案并不是一个好的解决方案。
您不应该使用在某个时候设置的全局变量,也不应该使用仅用于传播更改的 promise ,但 promise 应该代表这些值。这会带来更好的函数式编程风格。
就您而言:
var tpl = {
…
templatePromise: null,
load: function(template) {
this.templatePromise = $.get(this.templateUrl + template).then(function(response) {
console.log(this.template);
//Outputs the desired value
return response;
});
return this;
},
attachTo: function(el) {
$.when(this.templatePromise).done(function(template) {
// get the template here: ^^^^^^^^
console.log(template);
});
}
…
}
关于javascript - 以不同的方法等待 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23129285/