Aso Strife Aso Strife - 6 months ago 27
Ajax Question

How to make code wait while calling asynchronous calls like Ajax with returned value

I've read a lot of question about this topic. But nobody has my problem.
Actualy I have this in my main code:

// getHtmlInfoWindows has inside an ajax request
var infowindowString = getHtmlInfoWindow(selectedTrucks[i], true);
makeInfoWindowEvent(map, infowindow[i], infowindowString, markers[i], "click");


Here the getHtmlInfoWindows() code

$.ajax({
url: ajaxUrl,
})
.done(function(data) {
// some line of code and operation
return someData;
}


Basically I would to wait until getHtmlInfoWindow() finish and next execute makeInfoWindowEvent() but I don't know how.

I've tried this:

$.when(infowindowString = getHtmlInfoWindow(selectedTrucks[i], true)).done(function(){}


but doen't work because a have to return the intere ajax response and not the single value "someData" that I want.
How can I do?

Thanks guys

Answer

Pass the code you want to be executed as a callback function:

// getHtmlInfoWindows has inside an ajax request

var callback = function(data){ 
   makeInfoWindowEvent(map, infowindow[i], data, markers[i], "click"); 
}

getHtmlInfoWindow(selectedTrucks[i], true, callback);

and then call your callback when the ajax is done:

$.ajax({
    url: ajaxUrl,
})
.done(function(data) {
     // some line of code and operation
     callback(data);
}