我想在转到另一个循环之前先完成所有结果。我怎样才能实现这一目标?
function callback_Original(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker_Original(results[i]);
}
}
}
有时候总会占用很少的地方。
function createMarker_Original(place) {
var photos = place.photos;
if (!photos) {
return;
}
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div style="float:left"><img src="' + photos[0].getUrl({'maxWidth': 120, 'maxHeight': 120})
+ '"></div><div style="float:right; padding: 10px;"><b>Name: </b>'+ place.name +'<br/>'+
'<b>Coordinates : </b>'+ place.geometry.location +'<br/>'+
'<b>Type: </b>'+ type +'<br/>');
infowindow.open(map, this);
});
}
答案 0 :(得分:2)
使用Promise怎么样?(ES6代码)
function callback_Original(results, status) {
return new Promise((resolve, reject) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker_Original(results[i]);
}
resolve();
}else
reject("Places service error");
});
}
然后使用
callback_Original(a,b)
.then(response => {
// Loop finished, what to do nexT?
})
.catch(error => {
// Error
console.log(error);
});
答案 1 :(得分:0)
使用async
,它会等待promise
。 Reference
function callback_Original_child(results, status) {
return new Promise(resolve => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker_Original(results[i]);
}
}
});
}
async function callback_Original(results, status) {
try {
await callback_Original_child(results, status);
} catch (error) {
console.log(error);
}
}
callback_Original()