2

I have a problem with the Google DirectionsService. I know it's asynchronous and that is the cause of my troubles. I'd like to wait until the DirectionsService returns a result instead of executing code without an answer. Here is a sample:

function snap_to_road (lat) {
    var position;

    var request = {
        origin: lat,
        destination: lat,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            return response.routes[0].legs[0].start_location;
        }
    });
}

alert(snap_to_road(current.latLng));

The alert always shows: "undefined". Is there any way to solve this?

Andrew Leach
  • 12,945
  • 1
  • 40
  • 47
Martus0
  • 667
  • 1
  • 10
  • 16
  • You can use a jQuery AJAX call and set `async: false`, this will make your program wait until whatever resource you want has loaded. – Hunter McMillen May 27 '12 at 13:37
  • Could you show me some link to sample? I have never used such thing. – Martus0 May 27 '12 at 13:57
  • 1
    possible duplicate of [Will the function wait for the asynchronous functions completion before returning?](http://stackoverflow.com/questions/6284457/will-the-function-wait-for-the-asynchronous-functions-completion-before-returnin). AJAX is called *asynchronous* for a reason. Making it synchronous is a bad idea. – DCoder May 27 '12 at 13:57
  • Frankly speaking I dont how I can use this one in my case. – Martus0 May 27 '12 at 14:57

4 Answers4

5

I don't think that is possible. You could use a callback parameter in snap_to_road:

function snap_to_road (lat, callback) {
    var position;

    var request = {
        origin: lat,
        destination: lat,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            callback(response.routes[0].legs[0].start_location);
        }
    });
}

snap_to_road(current.latLng, function(result) {
    alert(result);
});
Rob
  • 156
  • 1
  • 10
0

You can make snap_to_road() return a Promise and then use await in a async function. The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code. Like this:

 function snap_to_road (lat) {
var position;

var request = {
    origin: lat,
    destination: lat,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};
return new Promise((resolve, reject) => {
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            resolve(response.routes[0].legs[0].start_location);
        }else{
            reject(0);
        }
    });
});

}

async function alertPromise(){
    await snap_to_road(current.latLng).then((resolve) => {
        alert(resolve)
    })
}

You can put some message in reject() and treat before.

-1

Call your alert method after google directions returns result. Like: Call snap_to_road after button click event.

function snap_to_road (lat) {
  var position;

  var request = {
    origin: lat,
    destination: lat,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      ShowAlert(response.routes[0].legs[0].start_location);
    }
  });
}

function ShowAlert(result){
  alert(result);
}
Craicerjack
  • 6,203
  • 2
  • 31
  • 39
Sumit
  • 136
  • 5
-2

Here is an example of what I mentioned above:

var path = "/path/to/some/resource";

$.ajax({
        url:    path,
        type: "get",
        data: serializedData,  //<-- depends on what data you are using
        async: false, //will wait until resource has loaded or failed 

         //will be called on success
        success: function(response, textStatus, jqXHR){
            // log a message to the console
            console.log("Successfully loaded resource!");
        },
         //will be called on error
        error: function(jqXHR, textStatus, errorThrown){
            // log the error to the console
            console.log(
                "The following error occured: "+
                textStatus, errorThrown
            );
        },
        // callback handler that will be called on completion
        // which means, either on success or error
        complete: function(){
            console.log("Completed: with error or success");
        }
    });
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170