[英]JavaScript/jQuery callbacks of functions
我有2個功能。
function f1() {
$.ajax(..., success: function(response) {
// some code executed whenever request is completed.
}
}
function f2() {
// my code
}
我需要一個接一個地調用這些函數。
f1() // waiting until ajax request in the function is complete.
f2()
我嘗試了$.when().then()
,但是似乎沒有用。
$.ajax
調用返回$.Deferred
實例,該實例用於跟蹤調用進度-這是您需要從f1
函數返回的內容。 然后.then()
您可以使用.then()
.done()
等。
編輯以回應評論
如果要在f1
內部以及從外部調用回調,則可以返回.pipe
方法的結果。
function f1() {
return $.ajax(/*...*/).pipe(function() {
//local 'done' handler
});
}
function f2(resultFromF1Handler) {
//...
}
f1().done(f2);
function f1(onsuccess)
{
$.ajax(
{
success: function(r)
{
// some code
onsuccess(r);
}
});
}
function f2()
{
// my code
}
f1(f2);
我建議在作為f1()成功執行的匿名函數中調用f2()。
這樣做有問題嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.