繁体   English   中英

JavaScript范围,从函数回调中中断

[英]JavaScript scope, break for cycle from function callback

如果proccess = true,我需要中断循环,但是它是不确定的。

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

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

到循环结束时,根据您的问题文本,您甚至没有收到第一个答复,因此您需要使用其他解决方案。

我的意思是,您将无法 中断周期 ,因为到周期结束时,您仍然不知道过程是否成立。

根据您的实现,您可能需要看一下Promise 尽管将整个内容包装在执行回调的函数中可能会更容易:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM