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

前端 未结 1 1091
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 04:52

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\

相关标签:
1条回答
  • 2021-01-07 05:51

    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
    });
    
    0 讨论(0)
提交回复
热议问题