Асинхронный цикл Javascript с вызовом ajax - PullRequest
0 голосов
/ 16 октября 2019

У меня есть вызов jQuery ajax, который я хочу выполнить по порядку после получения результата.

$.ajax({
    url : 'https://api.spacexdata.com/v3/launches',
    type : 'GET',
    dataType:'json',
    success : function(data) {  
       data.forEach(async function(element) {
          await console.log(element.flight_number);
          await auto(element.flight_number);
       });
    },
    error : function(request,error) {
        console.log(request,error);
    }
});

function auto(val) {
  $.ajax({
    url : 'https://api.spacexdata.com/v3/launches/latest',
    type : 'GET',
    dataType:'json',
    success : async function(data) {                     
      await console.log('second api called' , data);
    },
    error : function(request,error) {
        console.log(request,error);
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Выход:

 1
 2
 3
 4
 ...
 second api called Obj
 second api called Obj
 second api called Obj
 second api called Obj
 ...

, но ожидаемый результат:

1
the second api called 
2
the second api called 
3
the second api called   
4
the second api called 

....

вот это jsfiddle :

Есть ли у вас какие-либо идеи, что не так с циклом? Я хочу последовательность, которую я упомянул!

1 Ответ

1 голос
/ 16 октября 2019

Можете ли вы попробовать этот код

$.ajax({
  url : 'https://api.spacexdata.com/v3/launches',
  type : 'GET',
  dataType:'json',
  success : function(data) {  
    data.forEach(function(element) {
      console.log(element.flight_number);
       auto(element.flight_number);
    });
  },
  error : function(request,error) {
    console.log(request,error);
  }
});
    
async function auto(val) {

  const dataset= $.ajax('https://api.spacexdata.com/v3/launches/latest');
 console.log('second api called');
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...