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

Iterate for loop AFTER asynchronous callback inside has been invoked

本文关键字:迭代 for 循环 回调 内部 异步 调用      更新时间:2023-09-26
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循环外的警报,然后是异步函数内的警报。

我如何改变这一点,使for循环只移动到下一次迭代,一旦map.addMarker回调已经触发?我看过其他一些类似问题的问题,他们谈到为for循环提供闭包。我试过了,但是没有成功。

异步编程被认为是非阻塞的,这意味着在等待结果时不会暂停执行。所以你不能暂停for循环,直到函数完成。你可以这样写

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)
    }
}

recursive(0, c, stop, stopMarkers, map,function(){})