所以我需要两次 ajax 调用来获取所有数据。我正在使用 jQuery
的 ajax 调用来实现这一点。但是后来我对执行顺序有点困惑。这是我有问题的代码:
$.ajax({
type: "GET",
url: "/api/data",
dataType: "json"
}).then(function (data) {
console.log("I am the first")//correct
}).then(function () {
//second ajax
$.ajax({
type: "GET",
url: "/api/lifecyclephase",
dataType: "json"
}).then(function (data) {
console.log("I am the second")//third
})
}).then(function () {
console.log("I am the third")//second
})
输出是
I am the first
I am the third
I am the second
难道 then
不应该等待第二个 ajax
完成它的工作再继续吗?
正确的是:
$.ajax({
type: "GET",
url: "/api/data",
dataType: "json"
}).then(function (data) {
console.log("I am the first")
}).then(function () {
$.ajax({
type: "GET",
url: "/api/lifecyclephase",
dataType: "json"
}).then(function () {
console.log("I am the second")
}).then(function(){
console.log("I am the third")
})
})
最佳答案
在有问题的代码中,您只是缺少一个return
。
$.ajax({
type: "GET",
url: "/api/data",
dataType: "json"
}).then(function (data) {
console.log("I am the first");
}).then(function () {
return $.ajax({
^^^^^^
type: "GET",
url: "/api/lifecyclephase",
dataType: "json"
}).then(function (data) {
console.log("I am the second");
});
}).then(function () {
console.log("I am the third");
});
如果没有return
,就没有什么可以通知外部 promise 链内部 promise 的存在,因此外部链不会等待内部 promise 在进入第三阶段之前解决。
关于javascript - 在 then 函数中调用 Jquery ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53463808/