JavaScript作用域,函数回调循环中断

JavaScript作用域,函数回调循环中断,javascript,scope,cycle,Javascript,Scope,Cycle,如果process=true,我需要中断循环,但它是未定义的 var mapFound; var locations = {$addressTest}; for (var i = 0; i < locations.length; ++i) { getCoordinates( locations[i], function(proccess)

如果process=true,我需要中断循环,但它是未定义的

        var mapFound;
        var locations = {$addressTest};
        for (var i = 0; i < locations.length; ++i) {
            getCoordinates(
                    locations[i],
                    function(proccess) {
                    }
            )
            if(proccess) { break; }
        }
var-mapFound;
变量位置={$addressTest};
对于(变量i=0;i
问题似乎基本上是
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.
});
函数getCoords(位置、名称、回调){ 对于(变量i=0;i问题在于,当您使用
console.log(mapFound)
时,代码是异步的。映射尚未找到。是否有其他方法可以通过进程回调中断循环?您可以将
console.log
放在
mapFound=process旁边零件。你到底需要什么?我需要打破循环如果proccess=trueYes,getCoordinates是google api的“geocoder.geocode”方法,我会尝试使用你的解决方案,如果它有效,我会标记为答案。如果它不起作用,你可能想编辑你的答案,并包含
getCoordinates()
函数的源代码,这样我们就可以调试整个过程。