for (b; b < stops.length; b += 1) {
(function (b, c, stops, stopMarkers, map) {
var matchFound = false;
for (c; c < stopMarkers.length; c += 1) {
if (stopMarkers[c].code === stops[b].atcocode) {
// Already on the map
matchFound = true;
}
}
// If the stop isn't already on the map
if (!matchFound) {
map.addMarker({
icon: icons.busStop,
position: new plugin.google.maps.LatLng(stops[b].latitude, stops[b].longitude)
}, function (marker) {
alert("I SHOULD FIRE BEFORE LOOP HAS FINISHED!");
marker.code = stops[b].atcocode;
stopMarkers.push(marker);
});
}
})(b, c, stops, stopMarkers, map);
}
alert("I SHOULD FIRE AFTER LOOP HAS FINISHED");
目前,如果stops.length
等于1,则上述两个警报的顺序是for循环之外的警报,后面是异步函数内部的警报。
如何在map.addMarker
回调被触发后,for循环只移动到下一次迭代?我已经查看了其他一些类似问题的问题,并讨论了为for循环提供闭包的问题。我尝试过但没有成功。
答案 0 :(得分:0)
function recursive(b, c, stops, stopMarkers, map,callback) {
if(b==stopMarkers.length){
return true;
callback.call(this);
}
var matchFound = false;
for (c; c < stopMarkers.length; c += 1) {
if (stopMarkers[c].code === stops[b].atcocode) {
// Already on the map
matchFound = true;
}
}
// If the stop isn't already on the map
if (!matchFound) {
map.addMarker({
icon: icons.busStop,
position: new plugin.google.maps.LatLng(stops[b].latitude, stops[b].longitude)
}, function (marker) {
alert("I SHOULD FIRE BEFORE LOOP HAS FINISHED!");
marker.code = stops[b].atcocode;
stopMarkers.push(marker);
recursive(b+1, c, stops, stopMarkers, map,callback);
});
}
else{
recursive(b, c, stops, stopMarkers, map,callback)
}
}
递归(0,c,停止,停止运动,地图,函数(){})