我已经编写了从Google Place API获取Google地点信息的代码。我只想在系统完成循环中的所有AJAX调用时才调用displayHTML()
。
var placeid_json = [{
"placeid": 'ChIJcSlz1vtz6lIR6rXex3J9PFE',
"url": "/locations/northway-pharmacy-broadway"
}, {
"placeid": 'ChIJ515pxC5x6lIR8MKrpu1a6GY',
"url": "/locations/northway-pharmacy-brothers"
}, ];
function getLocationPerServicesFirstTime() {
console.log("getLocationPerServicesFirstTime called");
var counter = 0;
for (i = 0; i < placeid_json.length; i++) {
var service = new google.maps.places.PlacesService(map);
// var placeId = placeid_json[i].placeid;
googlePlacePromises.push(service.getDetails({
placeId: placeid_json[counter].placeid
}, function(result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
console.log(status);
return;
}
storeLocation = {
placeId: placeid_json[counter].placeid,
url: placeid_json[counter].url,
lat: result.geometry.location.lat(),
lng: result.geometry.location.lng(),
result: result,
}
storesInfo.push(storeLocation);
if ((placeid_json.length - 1) == counter) {
// console.log(storesInfo);
// console.log(counter);
// displayHTML();
}
counter++;
console.log("Google Place API called!");
}));
// console.log(googlePlaceService);
// googlePlacePromises.push(googlePlaceService);
}
$.when.apply(null, googlePlacePromises).done(function() {
console.log(storesInfo.slice());
console.log("All ajax call completed");
displayHTML();
});
console.log(googlePlacePromises);
}
答案 0 :(得分:0)
似乎您应该使用Promise.all()
Promise.all(googlePlacePromises).then(function(results) {
console.log('resolved promises: ', results);
});