Tuesday, 1 October 2013

Wait for the end of an asynchronous Javascript function to retrieve a result (Deferred ?)

Wait for the end of an asynchronous Javascript function to retrieve a
result (Deferred ?)

Ok guys, I know this topic has already been discussed multiple times, but
I can't find an answer to solve my problem.

So I'm trying to do a simple think : I'm creating a string, like :
distance is : " + CalculateDistance(position); The wanted result is
something like distance is 5kms (8min).
CalculateDistance(position) is a function calling a Google maps API called
DistanceMatrix to calculate distance between two points. The API is
documented here, and the given sample perfectly works. I adapted it like
this :
function CalculateDistance(position)
{
var service = new google.maps.DistanceMatrixService();
var destination = new google.maps.LatLng(/* some lat/lng */);
service.getDistanceMatrix(
{
origins: [position],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK)
{
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
distanceMatrixResult = results[0].distance.text + " ( " +
results[0].duration.text + " min)";
}
Oh, by the way, distanceMatrixResult is a global variable. In fact, I just
need to get the content of results[0].distance.text (and when I print it
in the console in callback(), the value is OK) and then concatenate the
value with "Distance is". If someone have a smarter solution, it is
welcomed !
The API call is asynchronous, and in my case, distanceMatrixResult is
always empty in the result string. But when I log its value in the
console, distanceMatrixResult value became the good one AFTER the string
was created.
All I want to write is :
• Call CalculateDistance (which call callback asynchronously)
• When callback is ended, concatenate the string with the
distanceMatrixResult value.
I tried some Deferred, like $.done() and $.when().then() but I can't
success...
Can someone help me ?
Thank you !

No comments:

Post a Comment