我有一个在循环中调用另一个函数的函数。另一个函数进行异步调用。如何等待或知道循环中的每个异步调用何时完成?我尝试在外部函数上进行实验并使用变量赋值,它将返回true,希望它等待该函数的所有内容完成,并在继续执行到下一行sortDrivers之前为变量赋值获取值(),但这似乎并没有像希望的那样发挥作用。
function getData() {
var url = encodeURI("viewData.aspx");
$.get(url, function (data) {
checkForLogin(data);
$("#ajaxResults").html(data);
checkForOrphans();
// setRoute loops making async calls, returns true when done
var holdUp = setRoute();
// should not execute until all async calls inside setRoute are done
sortDrivers();
});
}
// builds direction request for each driver
function setRoute() {
var drivers = $("#ajaxResults").find(".driverSection");
for (var x = 0; x < drivers.length; x++) {
var driver = $(drivers[x]).attr('id');
var dlat = $(drivers[x]).find('.dlat');
var dLatLng = new google.maps.LatLng($(dlat[0]).text(), $(dlat[0]).next().text());
var stops = [];
var transactions = $(drivers[x]).find(".transactions");
for (var y = 0; y < transactions.length; y++) {
var tlat = $(transactions[y]).find('.tlat');
var tLatLng = new google.maps.LatLng($(tlat[0]).text(), $(tlat[0]).next().text());
stops.push({ location: tLatLng, stopover: true });
}
request = {
origin: dLatLng,
destination: cLatLng,
waypoints: stops,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
// this will make an async call to directions service
getEtas(request, $(drivers[x]).attr('id'));
}
return true;
}
function getEtas(request, driver) {
var totalTime = 0;
var totalTimeDisplay = "";
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var tEtas = $("#" + driver).find('.tEta');
for (var x = 0; x < response.routes.length; x++) {
for (var z = 0; z < response.routes[x].legs.length; z++) {
var nextLeg = parseInt(response.routes[x].legs[z].duration.text);
if (z < response.routes[x].legs.length - 1 && z > 0) {
totalTime = totalTime + nextLeg + 3;
}
else {
totalTime = totalTime + nextLeg;
}
if (totalTime == 1) {
totalTimeDisplay = totalTime + " Min";
}
else {
totalTimeDisplay = totalTime + " Mins";
}
$(tEtas[z]).text(totalTimeDisplay);
}
}
var dEtas = $("#" + driver).find(".dEta");
$(dEtas[0]).text(totalTimeDisplay);
}
});
}