JavaScript for循環里邊異步操作問題。


問題:(DRIVING.search是異步操作)

for循環中做異步操作會導致aDistances數組里邊的數據全部都是從A_SHOP_INFO數組中最后一條數據獲取的值。

var iIdx = 0;
for(var i=0, len=A_SHOP_INFO.length; i<len; i++){
    var shopInfo = A_SHOP_INFO[i];
    DRIVING.search(new AMap.LngLat(shopInfo.shop_location_long,shopInfo.shop_location_lat), new AMap.LngLat(myLnglat[0],myLnglat[1]), function(status, result){
        var distance                         = new O_DISTANCE_INFO();
        distance.distance                     = result.routes[0]["distance"];
        distance.shop_id                     = shopInfo.shop_id;
        distance.shop_location_long         = shopInfo.shop_location_long;
        distance.shop_location_lat             = shopInfo.shop_location_lat;
        distance.shop_location_format_str     = shopInfo.shop_location_format_str;
        // aDistances[aDistances.length] = distance;
        aDistances.push(distance);
        iIdx++;
        if(iIdx == A_SHOP_INFO.length){ // 與所有店鋪導航距離計算完畢
            mylog("店鋪距離數組");
            mylog("'"+JSON.stringify(aDistances)+"'");
            // 計算距離最近的店鋪
            //mw_cal_min_distance(aDistances) ;
        }
    });
}

 

解決辦法:可以用$.each來代替for循環

 1 //定義變量來計算算出了幾個距離
 2 var iIdx = 0;
 3 //這里不使用for循環,是因為for循環中發生了異步請求之后,會導致所有異步請求成功之后的shopInfo都是最后一條數據。
 4 $.each(A_SHOP_INFO, function(i,shopInfo){
 5     DRIVING.search(new AMap.LngLat(shopInfo.shop_location_long,shopInfo.shop_location_lat), new AMap.LngLat(myLnglat[0],myLnglat[1]), function(status, result){
 6         var distance                         = new O_DISTANCE_INFO();
 7         distance.distance                     = result.routes[0]["distance"];
 8         distance.shop_id                     = shopInfo.shop_id;
 9         distance.shop_location_long         = shopInfo.shop_location_long;
10         distance.shop_location_lat             = shopInfo.shop_location_lat;
11         distance.shop_location_format_str     = shopInfo.shop_location_format_str;
12         // aDistances[aDistances.length] = distance;
13         aDistances.push(distance);
14         iIdx++;
15         if(iIdx == A_SHOP_INFO.length){ // 與所有店鋪導航距離計算完畢
16             mylog("店鋪距離數組");
17             mylog("'"+JSON.stringify(aDistances)+"'");
18             // 計算距離最近的店鋪
19 //                mw_cal_min_distance(aDistances) ;
20         }
21     });
22 });

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM