対象読者
- 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>