[英]How to wait for function to finish before running another one or rest of the code?
[英]Backbone Javascript: Wait for a function to finish before running another one
我是Java語言的新手,在閱讀了幾個示例之后,我仍然無法做到這一點。 我知道我需要使用回調,但是我的代碼無法正常工作。 這是我嘗試過的
$(this.el).html(this.template(), {
success: function() {
return this.collection.each(this.appendEntry);
}
});
success
從來沒有被稱為
好吧,如果您想在異步任務完成后執行某些操作,則可以使用promises。 以jQuery
為例:
$.when( myAsyncTask() )
.then(function(){
console.log("Executed when myAsyncTask() is done..");
});
如果您只想在成功獲取Collection數據時執行某些操作,請使用Backbone.Collection.fetch()
的success()
回調方法
myCollection.fetch({
success: function(data){
console.log("Your Collection data is available now.");
}
});
$(this.el).html()
(或更簡潔地說, this.$el.html()
)是一個同步函數調用。 在該功能完成之前,將不會執行其他Javascript代碼。
this.$el.html(this.template());
this.collection.each(this.appendEntry);
將按順序執行兩個語句。
您是否偶然以某種方式覆蓋了this.template()
template()
函數,在這種情況下this.template()
已變成異步調用? 如果是這樣,則需要在模板代碼中添加回調支持,並推遲html()
執行直到完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.