Reputation: 141
I am currently accessing a database through http requests, however in the function below, i am having issues as the request is completed after the data is needed.
$scope.submitUserName = function() {
console.log("button got clicked")
$http({
method: 'GET',
url: '/data/Graeham'
}).then(function successCallback(response) {
$scope.dataStuff = response;
console.log($scope.dataStuff);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
console.log($scope.formData.userName);
console.log($scope.dataStuff);
for (var i = $scope.dataStuff.data.length - 1; i >= 0; i--) {
if ( $scope.formData.userName == $scope.dataStuff.data[i].ASSIGNED_TO && $scope.dataStuff.data[i].PRIMARY_UCID == "Y" ) {
console.log($scope.dataStuff.data[i]);
console.log($scope.dataStuff.data[i].UCID)
$scope.assignedData.push($scope.dataStuff.data[i]);
$scope.assignedUCID.push($scope.dataStuff.data[i].SUSPECT_UCID);
}
}
console.log($scope.assignedData)
};
i cannot figure out what statement i need to ad to the http get to make it complete before moving onto the for loop.
Upvotes: 0
Views: 372
Reputation: 1252
JavaScript uses callbacks and it's not blocking, I think you are confusing it with standard imperative code.
I don't know which framework you are using but here's your current flow:
successCallback
and errorCallback
), which are two function which will be called either in case of success or error (one of the two, not both)As @linus-borg pointed out, the for loop needs to be inside the successCallback
, otherwise it will be called immediately after the GET request.
Upvotes: 0
Reputation: 23968
the for loop has to be in the successCallback
( or in a function called from there).
Upvotes: 3