Javascript 异步循环与 ajax 调用

标签 javascript asynchronous

我有一个 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 :

你知道循环出了什么问题吗?我想要我提到的序列!

最佳答案

你能试试这个代码吗

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

关于Javascript 异步循环与 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417179/

相关文章:

javascript - 多页使用 div 抛出未捕获错误 : cannot call methods on dialog prior to initialization; attempted to call method 'open'

javascript - 将变量与 Jquery 对象绑定(bind)的问题

c# - 如何通过回调等待外部响应?

javascript - 在 Angular 中执行前一个响应后执行一个函数

java - 暂停方法的执行,直到回调完成

javascript 使用indexOf搜索字符串

javascript - 如何禁用 html 或 JS 中的突出显示?

Javascript按属性分组对象

C++ boost::asio 如何在异步函数上正确使用 std::shared_ptr

r - 异步进程阻塞 R Shiny 应用程序