首页 > 解决方案 > 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,等等。而不是先加载。

任何帮助、建议、提示都会被应用。谢谢你。

标签: javascriptapifetch

解决方案


这将是一个很好的用途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,并将第ith 通道结果放在i数组中的subCounts索引处。


推荐阅读