0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

複数のAjaxのレスポンスを全て受け取ったら実行させる

Last updated at Posted at 2021-04-24

対象読者

  • async, awaitをソースに書くと死んじゃう病の人
  • jQueryの$.ajaxを利用する人

バージョン

jQuery: 3.6.0

追記

こっちのほうがいい

// 非同期処理1
const promise1 = $.ajax({
    url: 'https://httpbin.org/get?param=123'
})
.catch(e => {
    // エラー処理
    console.error(e);
    return e;
});

// 非同期処理2
const promise2 = $.ajax({
    url: 'https://httpbin.org/get?param=456'
})
.catch(e => {
    // エラー処理
    console.error(e);
    return e;
});

// 両方の非同期処理が完了したら次の処理を実行
Promise.all([promise1, promise2])
.then(dataArray => {
    console.log(dataArray);
})
.catch(e => {
    console.error("エラー発生");
});

こうする(追記前の記述)

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script>
// すべて終わったら
$.when(
    hogeAjax().then(function(data) {return data}),
    fugaAjax().then(function(data) {return data})
).then(function(hoge, fuga) {
    console.log(hoge.args.param);
    console.log(fuga.args.param);
}).catch(function(e) {
    console.log(e);
});

function hogeAjax() {
    return $.ajax({
        url: "https://httpbin.org/delay/5",
        type: "GET",
        data: {
            param: "ほげほげ",
        }
    });
}

function fugaAjax() {
    return $.ajax({
        url: "https://httpbin.org/delay/1",
        type: "GET",
        data: {
            param: "ふがふが",
        }
    });
}
</script>

類似記事

複数のAjaxを順番に実行させる
複数のAjaxの最初に受け取ったレスポンスに対して実行させる

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?