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

浪尽此生 提交于 2019-12-19 04:14:46

问题


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 !


回答1:


distanceMatrixResult is a global variable

It should not, it should be the value which your Promise (Deferred) stands for. This is the basic setup:

function calculateDistance(position) {
    var service = new google.maps.DistanceMatrixService();
    var destination = new google.maps.LatLng(/* some lat/lng */);
    var dfd = $.Deferred();
    service.getDistanceMatrix({
        origins: [position],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, function(response, status) {
        if (status == google.maps.DistanceMatrixStatus.OK)
            dfd.resolve(response);
        else
            dfd.reject(status);
    });
    return dfd.promise();
}

Now, you want to do

calculateDistance(…).then(function(response) {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var results = response.rows[0].elements;
    return results[0].distance.text + " ( " + results[0].duration.text + " min)";
}).done(function(distanceMatrixResult) {
    var myString = "distance is: "+distanceMatrixResult;
    // do something with your string now
});


来源:https://stackoverflow.com/questions/19125716/wait-for-the-end-of-an-asynchronous-javascript-function-to-retrieve-a-result-de

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!