继续等待循环增量,直到没有得到函数响应

时间:2016-01-21 09:14:04

标签: javascript

我有一个for循环和内部,我正在调用一个函数。但在循环变量的函数响应增加1之前。 我只想等到响应结束,然后将var增加1。

这是我的代码:

    for(var i=0;i<$scope.latitude.length;i++)
        {
              console.log("inside for :",$scope.latitude[i]);
              console.log("i after for:" ,i);
            console.log("count before if:" ,count);
                   if($scope.latitude[i]!=1)
                   {

                        console.log("inside if count is :",count);
                        console.log("i inside if:" ,i);
                            var lat =$scope.latitude[i];
                            var lng=$scope.longitude[i];

                       console.log("lat is going",lat);
                       console.log("lng is going",lng);



                        $scope.getDistance(lat,lng).then(function(response,flag){
                        console.log("flag is" ,flag);

                      setTimeout(function(){

                               flag="true";


                      },1000);

                var results = response.rows[0].elements;

                console.log(results[0].distance.text);
                console.log(results[0].duration.text);
                 return results[0].distance.text 


            }).done(function(distanceMatrixResult,flag) {
                    console.log("flag inside done is:" ,flag);

                      console.log("count is ",count);
                    console.log("i inside done:" ,i);
                     console.log(distanceMatrixResult);
         $scope.clients.treasureHunts[count].distance =distanceMatrixResult;   


                  $ionicLoading.hide();

                console.log("Results:->>>>>>>>>>>>", JSON.stringify( $scope.clients));

})

$scope.getDistance=function(lat,lng){
       console.log("lat inside google distance function:-" ,lat);
           console.log("lng inside google distance function:-" ,lng);

            var service = new google.maps.DistanceMatrixService();


        $scope.destinationDetails = {
            lat: lat,
            lng: lng
            }

            console.log("destination:-" ,JSON.stringify(  $scope.destinationDetails.lat));
         console.log("destination:-" ,JSON.stringify(  $scope.destinationDetails.lng));
           //getting current location
               var onSuccess = function (position) {

             console.log('Current Position: ', position.coords.latitude, ',', position.coords.longitude);
             $scope.originCenter = {

                lat: position.coords.latitude,
                lng: position.coords.longitude

            };
                        geocodeLatLng($scope.originCenter);
               }

               function onError(error) {
            console.error('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
            //alert('Error Occured' + error.message);
        }
        navigator.geolocation.getCurrentPosition(onSuccess, onError);/////////---------------------------------


              function geocodeLatLng(originCenter) {
                 console.log("destination inside function:-" ,JSON.stringify(  $scope.destinationDetails.lat));
         console.log("destination inside function:-" ,JSON.stringify(  $scope.destinationDetails.lng));


            $scope.originDetails = new google.maps.LatLng(originCenter.lat, originCenter.lng);
            console.log('Origin Details: ',JSON.stringify($scope.originDetails));
            $scope.finalDestination = new google.maps.LatLng($scope.destinationDetails.lat, $scope.destinationDetails.lng);
            console.log('destination details: ', JSON.stringify($scope.finalDestination));

            service.getDistanceMatrix(

                {
                    origins: [$scope.originDetails],
                    destinations: [$scope.finalDestination],
                    travelMode: google.maps.TravelMode.DRIVING,
                    unitSystem: google.maps.UnitSystem.METRIC,
                    avoidHighways: false,
                    avoidTolls: false
                },
                function (response, status) {
                    if (status !== google.maps.DistanceMatrixStatus.OK) {

                       console.error(JSON.stringify(response));
                       d.reject(response);



                    } else {
                        console.log("returning response ",JSON.stringify(response));
                        var flag="true";


                    d.resolve(response,flag);




                    }           


         });

1 个答案:

答案 0 :(得分:0)

由于js是单线程的(据此处所见),因此不能有循环等待js代码中发生的其他事情(就像执行的任何回调...)。

循环异步调用需要将功能拆分为异步回调/成功处理程序(也添加一些错误处理;),例如像这样:

function makeNextCall(i, total, onCompleted) {

  if( i >= total) {
    onCompleted();               // signal completion of whole iteration
  } else {
   makeAsyncCall(i, {                        // make the asynchronous call
     onSuccess : function() {                // define callback
      makeNextCall(i+1, total, onCompleted); // next iteration
    }
   }); 
  }
}