LoginSignup
2
4

More than 5 years have passed since last update.

jQueryでajaxを順番に実行するメモ

Last updated at Posted at 2019-01-23

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するのを毎回忘れるんですよね…。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4