“如何修复无序”;取回;在javascript中

“如何修复无序”;取回;在javascript中,javascript,for-loop,ecmascript-6,fetch,Javascript,For Loop,Ecmascript 6,Fetch,我正在使用for循环获取多个路由并保存其结果 这是我的密码 for (let i = 0; i < datesToFetch.length; i++) { fetch("http://localhost:3000/areaChart/"+datesToFetch[i]+"/"+datesToFetch[i+1]) .then(response => response.json()) .then(response => console.log(response)) }

我正在使用for循环获取多个路由并保存其结果 这是我的密码

 for (let i = 0; i < datesToFetch.length; i++) {


fetch("http://localhost:3000/areaChart/"+datesToFetch[i]+"/"+datesToFetch[i+1])
.then(response => response.json())
.then(response => console.log(response))

}
for(设i=0;iresponse.json())
.then(response=>console.log(response))
}
真正奇怪的是,我得到的数据顺序是随机顺序,而不是按照for循环的升序来的,这在本例中非常重要


我应该怎么做才能以正确的顺序获取数据?

欢迎使用异步代码

您可以做的一件事是创建一个名为
datesToFetch.length
long的空数组,并将
response.json()
的值分配给相应的索引

const responses = [...Array(datesToFetch.length)]

for (let i = 0; i < datesToFetch.length; i++) {
  fetch("http://localhost:3000/areaChart/"+datesToFetch[i]+"/"+datesToFetch[i])
    .then(response => response.json())
    .then(response => responses[i] = response)
}
const responses=[…数组(datesToFetch.length)]
for(设i=0;iresponse.json())
。然后(response=>responses[i]=response)
}
您的案例:

您正在调用具有不同解析时间的多个函数。这就像在麦当劳排队等候一样,一些gyus在你可以在自己之前或之后得到他的食物的同时到达

函数getRandomInt(最大值){
返回Math.floor(Math.random()*Math.floor(max));
}
功能显示(一){
返回新承诺((解决)=>{
设置超时(()=>{
决议(i);
},getRandomInt(1500));
});
}
对于(设i=0;i<5;i+=1){
显示(一)
。然后(x=>console.log('->',x));
}
发生了什么,以及如何修复: 您的代码正在排队等待一堆
fetch
e,但在继续循环的下一次迭代之前不会等待它们完成。他们可以按任何顺序完成

如果您希望循环每次都停止并等待,请将其包装在
async
函数中,然后
wait
获取

async function test() {

    for (let i = 0; i < datesToFetch.length; i++) {
        var response = await fetch("http://localhost:3000/areaChart/"+datesToFetch[i]+"/"+datesToFetch[i+1]);
        var responseJson = await response.json();
        console.log(responseJson);
    }

}
async函数测试(){
for(设i=0;i

模拟您的代码:
constdelay=t=>newpromise(resolve=>setTimeout(resolve,t));
异步函数测试(){
for(设i=1;i console.log(`Call#${i}已完成。`));
}
}

test()这是因为此获取调用将添加到JavaScript事件循环中。将显示返回结果的第一个,因此顺序可能不同于调用它们的顺序

要解决此问题,您应该查看wait操作符。
更多信息可在此处找到:

您收到的是随机订单,因为这些来源需要不同的时间来加载和交付。您可以将响应保存在一个数组中,然后在加载所有响应时对其进行排序,或者使用承诺或其他方式。。。在不知道获取什么的情况下很难说。你应该看看
Promise.all
,这将有助于你完成该任务添加
getRandomInt
函数的目的是什么?@Jim它只是一个类似
fetch
的异步函数示例,但实际上在代码段中起作用