qua1ity qua1ity - 5 months ago 11
AngularJS Question

Run function2 after function1 is complete

My controller consists of a function that makes two function calls to the service with some scope values gathered from the view.

$scope.sendValues = function () {
MyService.function1($scope.value1, $scope.value2);

for(var i = 0; i < $scope.arr.length; i++) {
$scope.value3 = $(".input" + i).val();
MyService.function2($scope.value3);
}
};


Both the service functions makes a http request and they look similar to this:

var tempID = 0;

var function1 = function (value1, value2) {
return $http({
method: 'POST',
url: "someUrl",
data: {
valeu1: value1,
value2: value2
}
}).success(function (response) {
tempID = response.data.id;
});
};


Now the second function needs the value "tempID" from function1.

var function2 = function (value3) {
return $http({
method: 'POST',
url: "anotherURL",
data: {
value3: value3,
tempID: tempID
}
});
};


The problem is that sometimes function2 runs before function1 is done, which results in tempID being the declared value of 0. How do i make sure function1 is done before function2 runs? i'm aware i can put function2 in function1 ones success/done, but then how do i get the view values which im looping through in the controller function.

Answer

You can make use of promises

var function1 = function (value1, value2) {
    return $http({
        method: 'POST',
        url: "someUrl",
        data: {
           valeu1: value1,
           value2: value2
       }
   }).then(function (response) {
       tempID = response.data.id;
       retrun tempID;
   });
};

var function2 = function (value3, tempID) {
return $http({
    method: 'POST',
    url: "anotherURL",
    data: {
        value3: value3,
        tempID: tempID
    }
 });
};

You will call like this

function1('some value1', 'some value2').then(function(id){
     function2('your value 3', id).then(function(resp){
          // whatever you want to do with this response
    });
});