简体   繁体   English

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

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

I need to break cycle if proccess = true, but it's undefined. 如果proccess = true,我需要中断循环,但是它是不确定的。

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

The problem seems to be basically that getCoordinates() makes an asynchronous call. 问题似乎基本上是getCoordinates()进行了异步调用。

By the time the loop is over you haven't received even the first response, based on your question text, so you need to use another solution. 到循环结束时,根据您的问题文本,您甚至没有收到第一个答复,因此您需要使用其他解决方案。

I mean by this that you won't be able to break the cycle , because by the time the cycle is over you still don't know if process is true. 我的意思是,您将无法 中断周期 ,因为到周期结束时,您仍然不知道过程是否成立。

Depending on your implementation you might want to take a look at promises . 根据您的实现,您可能需要看一下Promise Although it might be easier to wrap the whole thing in a function that executes a callback: 尽管将整个内容包装在执行回调的函数中可能会更容易:

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