for (var i = 0; i < items.length; i++) {
var item = items[i];
GMaps.geocode({
address: item.address+" "+item.city+" "+item.zip,
callback: function(results, status) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
markers_data.push({
id: item.id,
lat : latlng.lat(),
lng : latlng.lng(),
title : item.name,
icon : {
size : new google.maps.Size(32, 32),
url : icon
},
infoWindow: {
content : ''
}
});
}
}
});
var pro = new Promise(function(resolve, reject){
//...your code
callback: function(results, status) {
if (status == 'OK') {
// тест на кол-во записей в markers_data или на последнюю итерацию цикла
//если так то resolve(markers_data)
}
}
//...
}).then(function(markers_data){
//...
})
var list_of_items_to_process = [ 1, 2, 3, 4, 5 ];
function asyncMap(list, exec, callback) {
var processed = 0;
list.forEach(function(current, index, array) {
exec(current, index, array, innerCallback.bind(index));
})
function innerCallback(result) {
list[this] = result;
processed++;
if (processed === list.length) {
callback(list);
}
}
}
function processor(value, index, array, callback) {
var result;
setTimeout(function() {
result = value*Math.round(Math.random()*10);
console.log(result)
callback(result);
}, 500*value);
}
function mainCallback(values) {
console.log(values);
}
asyncMap(list_of_items_to_process, processor, mainCallback)
function asyncMap(list, exec, callback) {
var processed = 0;
list.forEach(function(current, index, array) {
exec(current, index, array, innerCallback.bind(index));
})
function innerCallback(result) {
list[this] = result;
processed++;
if (processed === list.length) {
callback(list);
}
}
}
function processor(value, index, array, cb) {
GMaps.geocode({
address: value.address + " " + value.city + " " + value.zip,
callback: function(results, status) {
if (status == 'OK') {
cb(results);
} else {
cb(false);
}
}
});
}
function mainCallback(values) {
values.forEach(function(value) {
if (!value) return;
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
markers_data.push({
id: value.id,
lat: latlng.lat(),
lng: latlng.lng(),
title: value.name,
icon: {
size: new google.maps.Size(32, 32),
url: icon
},
infoWindow: {
content: ''
}
});
});
}
asyncMap(items, processor, mainCallback)