【发布时间】:2014-04-17 23:35:53
【问题描述】:
我目前正在为承诺而苦苦挣扎,我认为我的概念有点错误。基本上我想做的是编写一个小模板处理程序。
它有一个 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'));
【问题讨论】:
-
这看起来还不错,也许你收到一个错误(无论结果类型如何都会调用done)。尝试使用 this.promise.then().fail() 方法来区分好的请求结果和坏的请求结果。
-
感谢@PeterAronZentai。确实是我的错。当我设置模板属性时,我弄乱了范围。这不再指代我的对象,而是指回调的范围。只需要使用代理。感谢您指出这个问题!
-
我不确定您的代码有什么问题目前需要澄清一下吗?
-
@BenjaminGruenbaum 已经解决了,请参阅我上面的评论 :) 但可以肯定。问题是我认为在处理我的
load()方法中的异步请求之前,我认为promise 上的done()方法已被触发,因为我的template属性是空的,尽管它应该由加载中的ajax 请求填充方法。最终结果证明这只是一个范围界定问题,与 deferred 无关。 -
如果它已经解决了 - 而不是编辑它,请将问题恢复到原始状态并发布关于您如何解决它的答案。
标签: javascript jquery promise jquery-deferred deferred