javascript - JS循环通过API中的获取
问题描述
好的,所以最近我一直在研究这段代码,我很困惑和沮丧,为什么它会随机排序输出。但后来我意识到它正在加载哪个频道加载速度最快,然后它的索引变为 0,下一个加载速度最快的,变为 1,下一个加载速度最快的变为 2,等等。
var channels = [
"UCIgnIPif1LQxkdbvBmGNNuA", // channel 1
"UC_Qs0JhHoysG4LItMgGMHHQ", // channel 2
"UC_puGdwVL1kc5VRhaZc6Arw", // channel 3
"UCQvwHZVCrljzvaLVX33Qaaw" // channel 4
];
var key = "cant share but i will tell you the output of the code"
var subCounts = [];
function getSubs(id, key){
for(var i = 0; i < channels.length; i++){
fetch('https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+channels[i]+'&key='+key+'')
.then(response => {
return response.json()
}).then(data => {
//name[i].innerHTML =
subCounts.push(data['items'][0].statistics.subscriberCount);
});
} // for loop close
}
setTimeout(function(){
console.log(subCounts);
// output example: 4, 5, 6, 7
// another output: 5, 7, 6, 4
// another output: 7, 4, 5, 6
}, 1500) // good enough for the fetch to load
它只是随机的(先加载先到先得)。
我想要它做什么: 我希望它根据频道的顺序加载。所以通道 1 需要先加载,然后是通道 2,然后是通道 3,等等。而不是先加载。
任何帮助、建议、提示都会被应用。谢谢你。
解决方案
这将是一个很好的用途Promise.all
(文档)
就像是:
Promise.all(
channels.map(
channel => fetch('https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+channel+'&key='+key+'')
)
)
.then(Promise.all((responses) => responses.map(response => response.json()))
.then(responses => {
// now responses is an array in order of the results that you can process as you wish
});
另一种方法是使subCounts
长度与 相同channels
,并将第i
th 通道结果放在i
数组中的subCounts
索引处。
推荐阅读
- ios - Microblink:在最新版本 4.9.1 中加载资源 uae_name_dictionary 失败
- java - 视图的行为是固定大小而不是使用 ConstraintLayout 基于屏幕的动态大小
- python - 如何在 pytest 中将自定义部分添加到终端报告
- php - 无法使用标签和 Base64在 Chrome 上下载 JPG 文件
- ios - 如何在不重复的情况下在 SwiftUI 中创建对象的实例?
- java - 检查一个类是否被另一个类通过字节码引用
- ios - 防止 UIStepper 为 0?
- php - PHP oci_bind_by_name 绑定函数返回参数 -1 不起作用
- java - 我想从手机的内部存储中获取我选择的文件大小(以 MB 为单位)。但 file.length() 总是返回 0
- python - 从 Azure Blob 存储读取 XML 文件