How to access data in callback function?
My problem is that I want to hit an external api with an asynch callback function in a loop, and I need access to the loop index in that callback function. In this case the external api is the Google Directions Service, but that really isn't the key point; could be any api whose signatures I can't control.
Anyway, my jQuery skills are only at the advanced beginner/intermediate level, but I managed to read up on the jQuery Deferred object and create code that serializes the asynch calls to Google's DirectionsService.route() method. It works, but I can't manage to get access to that index (ii in the code below) in the callback function (displayDirections() in the code below). I've tried several other approaches ... Deferred.resolveWith(), creating an array of deferred objects and calling the javascript apply() function on Deferred.when(), and a few others too.
But I'm stuck, finally. Devoid of ideas. I feel sure there's a way to make this happen. Can anyone help? Thanks in advance,
-Billy B
- function RenderPolyLinesOnMap()
- {
- for (var ii = 1; ii < Number(directionsItems.length) ; ii++)
- {
- var directionsItem = directionsItems[ii];
- var previousDirectionItem = directionsItems[ii - 1];
- var o = new google.maps.LatLng(...);
- var d = new google.maps.LatLng(...);
- $.when(routeDirectionsBetweenPoints({ origin: o, destination: d, travelMode: google.maps.DirectionsTravelMode.DRIVING }))
- .then(displayDirections);
- }
- }
- function routeDirectionsBetweenPoints(directionsRequest)
- {
- var deferred = $.Deferred();
- DirectionsService.route(directionsRequest, deferred.resolve);
- return deferred.promise();
- }
- function displayDirections(response, status) {
- if (status === google.maps.DirectionsStatus.OK)
- {
- var polyLineOptionsForSegment = getPolyLineOptionsForSegment(directionsItem);
- DirectionsDisplay.setOptions({ map: Map, polylineOptions: polyLineOptionsForSegment });
- DirectionsDisplay.setDirections(response);
- }
- else
- {
- alert(status);
- }
- }