views:

161

answers:

1

How do I handle asynchronous calls to make sure they do not overlap?

This is my scenario---

I have a loop and within the loop I make a call to a google API and specify a call back function. My callback function processes the results and writes the output to a table.

However I have noticed that the results being written to the table seem to overlap or get mixed up i.e say I call the API at loop counter = 10, the result for loop counter = 10 may appear in the table beside the value for loop counter = 15.

How do I ensure that my callback function does not overlap? My code is written in javascript.

Also can anyone point me to a good and easy to understand documentation on asynchronous calls?

+2  A: 

Your functions don't overlap, you just don't know which one fetches the result first.

You can declare your functions so they accept the loop counter and pass it when you call them so you know where to write the result from the function.

Vasil
thanks Vasil. I finally figured it out. I'm now passing the loop counter across and it has solved the problem
You are welcome.
Vasil