Don’t worry, it happens to a lot of functions
Recently, while building an app that used a lot of ajax calls, we kept on running into the problem of an ajax call firing before the function above it finished. Given that the function above provided variables that were necessary in our ajax call, this broke everything.
My team and I scoured the internet (i.e. stack overflow) for an answer, but came up with nothing. We finally asked a Flatiron School TA, and she gave a us a great solution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
The getStopPoint function goes through the polyline (we’re dealing with the lovely Google Maps API here) and finds the stopping point. The most important part of the getStopPoint function is where we define our stopPointLat and stopPointLon variables. Those are the lat/lng coordinates we’re going to send to the Yelp API via the ajax call. But, alas, alack! All is going to break if the ajax train leaves the station without its lat/lng coordinates!
How we went about fixing this was by using a check_done variable that is set to “not done” when it is defined. It only changes to “done” once stopPointLat and stopPointLon have their values. We use an if/else statement inside the check function to make sure that check_done === “done” before we send off our ajax call. Else, we setTimeout and run the check function all over again.
I hope that helps anyone out there who might have this problem!