JQuery AJAX вызов внутри функции тогда - PullRequest
0 голосов
/ 25 ноября 2018

Так что мне нужны два вызова 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")
  })
})

Ответы [ 2 ]

0 голосов
/ 25 ноября 2018

В проблемном коде вы просто пропускаете 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 нет ничего, что бы сообщало цепочке внешнего обещания о выходе из внутреннего обещания, следовательно, внешней цепочкене ждет, пока внутреннее обещание успокоится, прежде чем перейти к третьему этапу.

0 голосов
/ 25 ноября 2018

«Второй» $.ajax инициализируется во втором .then, но $.ajax не не связан с чем-либо еще - интерпретатор инициализирует запрос ивот и все, поэтому, когда достигнут конец второго .then, next .then (third) выполняется немедленно.

Попробуйте return во втором Обещаниивместо этого - последующий .then будет только ждать разрешения Promise, если этот Promise будет возвращен предыдущим .then:

.then(function (data) {
   console.log("I am the first")//correct
})
.then(function () {
  //second ajax
  return $.ajax({
  // ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...