第一次使用promises。我正在使用google maps api来删除标记之间的setTimeout延迟标记然后聚类标记。我有两个承诺。一个用于从一个位置解析单个标记对象,另一个用于返回标记对象数组以进行聚类。在控制台中我看到console.log('markers before clustering');
转储之前我看到console.log('iteration: [' + timeout + '] value: [' + value +']');
告诉我.then
在resolve
返回之前正在执行。
在我的代码中,markers
是一个空白变量,locations
是预先定义的lat / lng对象。
这是控制台输出:
聚类前的标记
maps.js:52 [未定义,未定义,未定义,未定义]
maps.js:回调后的77个标记
maps.js:78 [未定义,未定义,未定义,未定义]
maps.js:69迭代:[0]值:[[object Object]]
maps.js:69迭代:[1]值:[[object Object]]
maps.js:69迭代:[2]值:[[object Object]]
maps.js:69迭代:[3]值:[[object Object]]
CODE:
function dropMarkers(markers) {
//locations are passed in from php json. variable is defined/populated prior to this .js file.
let test = new Promise(function(resolve, reject) {
markers = locations.map(addMarkerWithTimeout);
resolve(markers);
});
test.then(function(value){
console.log('markers before clustering');
//console dump is showing that markers are being populated correctly. I believe the problem is with the .push method above
console.log(value);
clustering(value);
});
}
function addMarkerWithTimeout(position, timeout) {
let prom = new Promise(function(resolve, reject) {
window.setTimeout(function(){
resolve(new google.maps.Marker({
position: position,
map: map,
animation: google.maps.Animation.DROP}));
}, timeout*300);
});
prom.then(function(value) {
console.log('iteration: [' + timeout + '] value: [' + value +']');
return value;
});
}
//add a marker clusterer to manage the markers.
function clustering(markers) {
console.log('markers after callback');
console.log(markers);
markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'images/m'});
}
答案 0 :(得分:0)
在dropMarkers中,您希望等待所有标记解析 - 为此,Promise.all
是首选武器:
function dropMarkers(markers) {
//locations are passed in from php json. variable is defined/populated prior to this .js file.
Promise.all(locations.map(addMarkerWithTimeout))
.then(function(value){
console.log('markers before clustering');
//console dump is showing that markers are being populated correctly. I believe the problem is with the .push method above
console.log(value);
clustering(value);
});
}
如果你打电话给dropMarkers,并想等待"等等"在完成时,只需return Promise.all ...
并使用
dropMarkers([]).then( ...
在addMarkerWithTimeout
中 - 您想要返回Promise
function addMarkerWithTimeout(position, timeout) {
return new Promise(function(resolve, reject) {
window.setTimeout(function(){
resolve(new google.maps.Marker({
position: position,
map: map,
animation: google.maps.Animation.DROP
}));
}, timeout*300);
})
.then(function(value) {
console.log('iteration: [' + timeout + '] value: [' + value +']');
return value;
});
}
我希望这会有所帮助