【发布时间】:2017-08-04 12:23:51
【问题描述】:
我已经检查了有关此问题的所有类似问题,但仍然无法弄清楚它应该如何工作。谁能带领我朝着正确的方向前进。 data 和 data2 没有按时加载,但是在我跳过 $.when 部分后它们出现在 chrome 调试器中。提前致谢。
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
};
【问题讨论】:
-
@Liam OP 正在使用 Promise 和
$.when()所以恕我直言不正确的 dup 目标 -
the answer 中有一个完整的部分 ES2015+: Promises with then() @Satpal
-
注意:success / error / complete 现在已被弃用,最好使用 done / fail / always
标签: jquery ajax asynchronous jquery-deferred