我已經檢查了關於這個問題的所有類似問題,但仍然無法弄清楚它應該如何工作。任何人都可以帶領我走向正確的方向。 data和data2沒有按時加載,但在跳過$ .when之後,它們出現在chrome調試器中。提前致謝。JQuery兩個不同的異步ajax調用返回undefined
function First (number) {
return $.ajax({
url: "/…",
data: { 'number': number },
type: "POST",
cache: "False",
success: function (data) {
return data;
},
error: function (xhr, type) {
alert('Something went wrong.')
}
});
}
function Second (number) {
return $.ajax({
url: "/…",
data: { 'number': number },
type: "POST",
cache: "False",
success: function (data2) {
return data2;
},
error: function (xhr, type) {
alert('Something went wrong.')
}
});
}
function DoSomeBusiness(number) {
$.when(First(number), Second(number)).then(function (data, data2) {
var someData = data; // data and data2 is undefined for sometime but right after I pass this line of code they appear correctly but i cannot use them cause they’re not loading on time.
var someData2 = data2;
});
.. do some business
};
可能重複的[如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-我回復了異步調用的響應) – Liam
@Liam OP正在使用Promise和'$ .when()',所以恕我直言不正確的dup目標 – Satpal
[答案]中有一整段(https:/ /stackoverflow.com/a/14220323/542251)* ES2015 +:承諾然後()* @Satpal – Liam