jQueryのDeferredで毎回ハマるので自分用にメモ。
サンプルの仕様
日付のリストから日付を順番に取り出して、対象データをAPIから取得する。
日付が新しい順に格納されているので、順番を担保する必要があります。
サンプルコード
var target_dates = [
"2019-01-23",
"2019-01-22",
"2019-01-21",
"2019-01-20",
"2019-01-19"
];
function getItems() {
var d = $.Deferred();
var target_date = target_dates.shift();
var postData = {
target_date : target_date
};
$.ajax({
type: 'POST',
url: 'api.php',
timeout: 10000,
cache: false,
data: postData,
dataType: 'json',
}).done(function(response) {
console.log(response);
d.resolve();// 通信が終了したら次へ
}).fail(function() {
alert('通信エラーが発生しました。');
});
return d.promise();
}
$(function() {
// 順番に実行
$.when(getItems())
.then(function() {
return getItems();
})
.then(function() {
return getItems();
})
.then(function() {
return getItems();
})
.then(function() {
return getItems();
});
});
メモ
.then()の中でreturnするのを毎回忘れるんですよね…。