2014-03-28 112 views
0

打破循環,我需要打破循環,如果proccess =真實的,但它是不確定的。JavaScript的範圍,從回調函數

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

的問題是,代碼是異步的,當你使用'的console.log(mapFound)'地圖一直沒有找到了。 – aurbano

+0

是否有任何其他方法,如何通過proccess回調週期的突破? – MyMomSaysIamSpecial

+0

你可以放置'旁邊'mapFound =過程console.log';'一部分。你究竟需要什麼? – aurbano

回答

1

問題似乎基本上是getCoordinates()進行異步調用。

通過循環結束後,您沒有收到甚至第一個響應,根據您的問題文本,所以你需要使用其他解決方案的時間。

我想說的是,你不會能夠打破這個循環,因爲週期結束後,您仍然不知道如果過程是真實的時間。

根據您的實現,你可能想看看promises。雖然它可能會更容易包裹在執行的回調函數整個事情:

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

是的,getCoordinates是谷歌API的「geocoder.geocode」方法,我會嘗試使用您的解決方案,如果它的工作我會標記爲答案。 – MyMomSaysIamSpecial

+1

如果它不起作用,您可能需要編輯您的答案幷包含'getCoordinates()'函數的源代碼,以便我們可以調試整個問題。 – aurbano