-1

I have an AngularJS function case where my $http runs even before my first function is finished

Here is an example format of my code:

$scope.function =  function(){
    $scope.functionOne(); // This function declares all the scope variable that I need to produce to throw on my API
    $scope.functionTwo(); // This is the function that throws a request to my API via $http.post
}

I need those variables but every variable is just a blank string when it reaches to my backend because $http throws a request before the first function finishes

UPDATE

$scope.functionOne = function(){
var geocoder = new google.maps.Geocoder();
if(geocoder){
    // console.log("dean")
    // console.log($scope.dealership.address);
    // console.log($scope.dealership.suburb)
    geocoder.geocode({
        'address': $scope.dealership.address + ', ' + $scope.dealership.suburb || "1/53 Township Drive, West Burleigh"
    }, function(result, status){
        // console.log("armada");
        // console.log(status);
        if(status == google.maps.GeocoderStatus.OK){
            console.log(result);

            var center_lat = result[0].geometry.location.lat();
            var center_lng = result[0].geometry.location.lng();

            var lat = result[0].geometry.location.lat();
            var lng = result[0].geometry.location.lng();

            $scope.$apply();
        }

        $scope.map.center.latitude = center_lat;
        $scope.map.center.longitude = center_lng;

        $scope.map.markers.pop();
        $scope.map.markers.push({
            latitude: lat,
            longitude: lng
        });
        $scope.dealership.latitude = lat;
        $scope.dealership.longitude = lng;

        $scope.$apply();
    });
}
};

$scope.functionTwo = function(){
    $scope.loadingData = true;
  // The code below is a factory on a scope variable
  $scope.dealership.create().then(function(response){

});
}
Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116

2 Answers2

0

The better option for depending function call is to use CallBack function.

Try to call your second function in the callback function of first function.

EDIT:

The another approach of angular is using Promises

You can refer more about it at https://docs.angularjs.org/api/ng/service/$qenter link description here

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0

Promises is the way to go. Once you are done with functionOne resolve the variables and then return the promise. Once the promise is successfully resolved run the second method.

Hope this helps

Happy Learning

Vatsal

Vatsal
  • 2,068
  • 4
  • 21
  • 24