JavaScript范围,从函数回调中断for循环

JavaScript scope, break for cycle from function callback

本文关键字:中断 for 循环 回调 函数 范围 JavaScript      更新时间:2023-09-26

如果process = true,我需要打破循环,但它是未定义的。

        var mapFound;
        var locations = {$addressTest};
        for (var i = 0; i < locations.length; ++i) {
            getCoordinates(
                    locations[i],
                    function(proccess) {
                    }
            )
            if(proccess) { break; }
        }

问题似乎基本上是getCoordinates()进行异步调用。

当循环结束时,你甚至没有收到基于你的问题文本的第一个响应,所以你需要使用另一个解决方案。

我的意思是你不会能够打破循环,因为当循环结束时,你仍然不知道如果进程是真的

根据你的实现,你可能想看看承诺。尽管将整个过程包装在一个执行回调的函数中可能更容易:

function getCoords(locations, name, callback){
    for (var i = 0; i < locations.length; i++) {
        getCoordinates( locations[i], name,
            function(proccess) {
                if(process){
                    console.log("Map found in "+locations[i]);
                    callback.call();
                }
            }
        );
    }
}
getCoords({$addressTest}, {$name}, function(){
    // Place here whatever you want to do once the map is found.
    // you can get the map location by passing it as an argument for the callback.
});