【问题标题】:Jquery ajax call inside a then function在 then 函数中调用 Jquery ajax
【发布时间】: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


    【解决方案1】:

    “第二个”$.ajax 在第二个 .then初始化,但 $.ajax 没有链接与其他任何东西 - 解释器初始化请求就是这样,所以当第二个.then 结束时,next .thenthird)立即执行。

    尝试 return 代替第二个 Promise - 如果之前的 .then 返回 Promise,则后续的 .then 只会等待 Promise 解决:

    .then(function (data) {
       console.log("I am the first")//correct
    })
    .then(function () {
      //second ajax
      return $.ajax({
      // ...
    

    【讨论】:

      【解决方案2】:

      在有问题的代码中,您只是缺少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不会等待内部promise解决,然后进入第三阶段。

      【讨论】:

        猜你喜欢
        • 2011-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2012-03-14
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        相关资源
        最近更新 更多