简体   繁体   English

jQuery ajax调用then函数

[英]Jquery ajax call inside a then function

So I need two ajax calls to get all the data. 所以我需要两个ajax调用来获取所有数据。 I am using jQuery 's ajax call to achieve that. 我正在使用jQuery的ajax调用来实现这一点。 But then I am a bit confused at the execution order. 但是,我对执行顺序有些困惑。 Here is my problematic code: 这是我有问题的代码:

$.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
 })

The output is 输出是

I am the first
I am the third
I am the second

Should not the then wait for the second ajax to finish its job before proceeding? then是否不应该等待第二个ajax完成其工作才能继续?

The correct one: 正确的:

$.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")
  })
})

The "second" $.ajax is initialized within the second .then , but that $.ajax isn't chained with anything else - the interpreter initializes the request and that's it, so when the end of the second .then is reached, the next .then (the third ) executes immediately. “第二个” $.ajax在第二个.then初始化 ,但是$.ajax没有与其他任何东西链接 -解释器初始化请求,就是这样,因此当第二个.then结束时, next .thenthird )立即执行。

Try return ing the second Promise instead - a subsequent .then will only wait for a Promise to resolve if that Promise is returned by the previous .then : 尝试return第二个.then一个后续的.then如果前一个.then返回该Promise .then则仅等待Promise解析:

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

In the problematic code, you are simply missing a return . 在有问题的代码中,您只是错过了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");
});

Without the return , there's nothing to inform the outer promise chain of the inner promise's exitence, hence the outer chain does not wait for the inner promise to settle before proceeding to the third stage. 没有return ,就没有任何东西可以告知外部承诺链内部承诺的退出,因此,外部链不会等待内部承诺解决才进入第三阶段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM