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

 

  

posted @ 2016-11-07 15:15  勇猛的小黑  阅读(5934)  评论(0编辑  收藏  举报