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

限于喜欢 提交于 2019-12-01 01:55:56

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