迭代循环后调用内部异步回调

时间:2014-06-01 13:32:00

标签: javascript

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循环提供闭包的问题。我尝试过但没有成功。

1 个答案:

答案 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,停止,停止运动,地图,函数(){})

相关问题