【发布时间】:2019-04-27 01:50:29
【问题描述】:
所以我需要两次 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")
})
})
【问题讨论】:
标签: javascript jquery ajax promise