[英]Waiting for promises in different methods
我目前正在為承諾而苦苦掙扎,我認為我的概念有點錯誤。 基本上我想做的是編寫一個小模板處理程序。
它有一個 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'));
結果證明這是一個范圍界定問題。 deferreds 沒有任何問題,但是我分配了值的實例的范圍。
load: function(template) {
this.promise = $.get(this.templateUrl + template, function(response){
this.template = response;
console.log(this.template);
//Outputs the desired value
});
return this;
},
在這里,我為this.template
分配了一個值。 但是我不在我的對象范圍內,而是在$.get()
方法的關閉范圍內。 因此,其他方法無法從屬性中提取值,因為它從未存儲在那里。
我想出了:
load: function(template) {
var self = this;
this.promise = $.get(this.templateUrl + template, function(response){
self.template = response;
});
return this;
},
我首先將對象實例實例分配給self
變量並在閉包中引用它而不是使用this
。 為了更優雅地解決它,還可以使用$.proxy()
。
就這樣。 這只是一個范圍界定問題,而不是一個延期問題。
雖然您自己已經確定了問題,但建議的解決方案並不是一個好的解決方案。
你不應該使用在某個時候設置的全局變量,也不應該使用承諾只是為了傳播更改,但承諾應該代表這些值。 這導致了更好的函數式編程風格。
在你的情況下:
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);
});
}
…
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.