如何在调用具有返回值的异步调用(如 Ajax)时使代码等待



我读过很多关于这个话题的问题。但是没有人有我的问题。实际上,我的主代码中有这个:

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

这里是 getHtmlInfoWindows() 代码

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

基本上我会等到getHtmlInfoWindow()完成,然后执行makeInfoWindowEvent(),但我不知道怎么做。

我试过这个:

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

但不起作用,因为必须返回 intere ajax 响应,而不是我想要的单个值"someData"。我该怎么办?

谢谢大家

将要执行的代码作为回调函数传递:

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

然后在 ajax 完成后调用您的回调:

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

最新更新