What's going on, and how to fix it:
Your code is queueing up a bunch of fetches, but not waiting for them to finish before moving on to the next iteration of the loop. They can finish in any order.
If instead you wanted the loop to stop and wait each time, wrap it in an async function, and await the fetch.
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);
}
}
A simulation of your code:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
async function test() {
for (let i = 1; i <= 5; i++) {
console.log(`Starting call #${i}`);
delay(5000 - (i * 1000))
.then(() => console.log(`Call #${i} has completed.`));
}
}
test();
A simulation of the solution provided above:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
async function test() {
for (let i = 1; i <= 5; i++) {
console.log(`Starting call #${i}`);
await delay(5000 - (i * 1000));
console.log(`Call #${i} has completed.`);
}
}
test();
Promise.all, this would help you with that task