我有一個自定義循環,在進入下一次迭代之前需要執行一個函數。這是代碼:jQuery .when()在循環中被忽略
function customIteration(arr, i)
{
if (i==arr.length) return;
var message = arr[i];
jQuery('#stepTwo #num1StepTwo').html('Expires: ' + $num1);
jQuery('#stepTwo #num2StepTwo').html(jQuery(message).find('.num2').text());
jQuery('#stepTwo #num3StepTwo').html(jQuery(message).find('.num3').text());
i++;
jQuery.when(mySpecialFunction()).then(customIteration(arr, i));
}
mySpecialFunction():
function mySpecialFunction(){
return jQuery.ajax({
url: "https://api.site.com/customurl",
dataType: "jsonp",
data: { data1: $data1, data2: $data2 },
success: function (data) {
...some code...
},
error: function (e) {
...some other code...
}
});
}
問題是,我在小提琴手看到網址是由上述循環的所有實例馬上打,而無需等待獲得來自mySpecialFunction()中的ajax代碼的響應。這當然會弄亂我應該得到的結果。
將'.then(customIteration(arr,i))'改爲'.then(function(){customIteration(arr,i)})''。 – A1rPun
@ A1rPun這實際上工作!非常感謝。 – user2413079