javascript - 带有ajax调用的Javascript异步循环
问题描述
我有一个 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>
推荐阅读
- vb.net - 在 vb.net 控制台应用程序中使用 URL 下载私有 Github 存储库
- java - 在 AWS Lambda (Java) 上的另一个线程上运行时出现 SSLHandshakeException
- android - java.lang.OutOfMemoryError 处理来自 Camera 的 14 个数据
- asp.net - 使用 System.IO.MemoryStream 处理相对较大的 zip 档案
- ssl - 在 thingsboard 上启用 HTTPS
- visual-studio - D9035 的替换:选项“Gm”已被弃用(最小重建)
- c - C 主函数变体
- r - 如何在 R 包中组织内部依赖项?
- regex - 只是想用正则表达式读取文件名,但看起来我写的不是 wokring
- typescript - 如何使用 TypeScript 将对象类型数组转换为平面对象类型?