how to fix unordered "fetch" in javascript

1050 views javascript
-2

I am fetching multiple route using for loop and saving its result this is my code

 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))

}

whats really weird that order of data that I am getting is coming random order it is not coming according to for loop ascending order which is really important in this case

what should I do so I get data in proper order ?

answered question

2 Answers

11

Welcome to asynchronous code!

One thing you can do is create an empty array that is datesToFetch.length long, and assign the value of response.json() to the appropriate index.

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)
}

posted this
1

Your case

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function display(i) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(i);
    }, getRandomInt(1500));
  });
}

for (let i = 0; i < 5; i += 1) {
  display(i)
    .then(x => console.log('->', x));
}


One soluce

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function display(i) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(i);
    }, getRandomInt(1500));
  });
}

const promises = [];

for (let i = 0; i < 5; i += 1) {
  promises.push(display(i));
}

// We use Promise.all to wait for all responses
// The responses are in the call order
Promise.all(promises)
  .then((rets) => {
      rets.forEach(x => console.log('->', x));
  });

posted this

Have an answer?

JD

Please login first before posting an answer.