0

I could not get the index right of for loop when I asynchronous function inside a for loop. Here is my code:

for (var i = 0; i < details.waypoints.meta.length; i++) {
    for (var j = start_index; j < i; j++) {
        (function (cntr) {
            fs.readFile(Path.join(__dirname, "/../../Modified_Data.json"), "utf8", function readFileCallback(err, data) {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    console.log(cntr) //printing the index
                }
            });
        })(j);
    }
}      

The index I am getting are which are not in right order: 1 3 0 2 4 5 6 7 8 9

novalagung
  • 10,905
  • 4
  • 58
  • 82
Developer
  • 255
  • 5
  • 18
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Apr 20 '17 at 08:28
  • Possibly better actually [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Liam Apr 20 '17 at 08:29
  • 5
    Asynchronous operations take an arbitrary amount of time. _Their results will not be "in order"_. – evolutionxbox Apr 20 '17 at 08:30
  • using Promises you can kick off all the asyncrhonous requests, and get the results in order once the last request completes – Jaromanda X Apr 20 '17 at 08:31

1 Answers1

0

You can use promises and the Promise.all function to fire off a bunch of asynchronous requests and get the results in the order they were requested if all succeed. It doesn't look like you are using any of the loops values accept the index.

const readFilePromise = x => new Promise((resolve, reject) => {
  const path = Path.join(__dirname, "/../../Modified_Data.json")
  fs.readFile(path, 'utf8', (err, data) => {
    if (err) {
      return reject(err)
    }
    resolve(data)
  })
})

Promise.all(
  details.waypoints.meta.map(readFilePromise)
)
.then(data => {
  data.forEach((x, i) => console.log(x, i))
})
.catch(err => console.error(err))
synthet1c
  • 6,152
  • 2
  • 24
  • 39