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