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.
3 Answers 3
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
});
});
Comments
Callback is asynchronous in nature. It is obvious that sometimes 2 will run before 1. To solve the problem, include these functions into closures. Closures will execute these functions in order i.e. synchronously.
Comments
This should work. But for elegance, promises, callbacks could be a better design.
var function1 = function (value1, value2) {
return $http({
method: 'POST',
url: "someUrl",
data: {
valeu1: value1,
value2: value2
}
}).success(function (response) {
tempID = response.data.id;
for(var i = 0; i < $scope.arr.length; i++) {
$scope.value3 = $(".input" + i).val();
MyService.function2($scope.value3);
}
});
};
function2receive the entire POST response, so that it can get any data it likes from the transaction?