javascript - 在 then 函数中调用 Jquery ajax

标签 javascript jquery ajax promise

所以我需要两次 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/

相关文章:

javascript - 使用 jQuery 迭代特定的 CSS-id

javascript - 如何更改表中行的颜色(SAPUI5)?

javascript - 我的 ajax post 请求被调用两次

javascript - 如何在angular的$http中添加ajax的dataType属性?

javascript - DHTML 菜单不显示

php - 拖放保存到 mysql 优化

javascript - 运行网站上显示的计数器

javascript - javascript中的表单验证代码错误

javascript - 删除空格但在文本区域中保留换行符 JS 或 jQuery

javascript - 如何使用 Javascript、URL 和 key 对数据库进行 ajax 调用