0

I have a for loop and inside that I am calling one function. But before function response for loop variable is incremented by 1. I just want to wait until the response has come, then increment var by 1.

Here is my code:

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




                    }           


         });
Ashish Sinha
  • 111
  • 9

1 Answers1

0

Since js is single threaded (as far as regarded here) there can not be a loop waiting for something other happening in js code (like any callbacks executed..).

Looping over asynchronous calls need to split functionality into the async callback/success-handler (add some error handling as well;), e.g. like this:

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
    }
   }); 
  }
}
fast
  • 885
  • 7
  • 15