0

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.

jcubic
  • 61,973
  • 54
  • 229
  • 402
Graeham Broda
  • 131
  • 1
  • 6
  • 15
  • Look into this question [How to $http Synchronous call with AngularJS](http://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs) – jcubic Jul 21 '16 at 14:19

2 Answers2

3

the for loop has to be in the successCallback ( or in a function called from there).

Linus Borg
  • 23,622
  • 7
  • 63
  • 50
0

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:

  1. main function is called
  2. a GET request is issued, and the result is a Promise
  3. the promise accept two parameters (successCallback and errorCallback), which are two function which will be called either in case of success or error (one of the two, not both)
  4. ERROR: immediately after your get has been requested, you start your for loop

As @linus-borg pointed out, the for loop needs to be inside the successCallback, otherwise it will be called immediately after the GET request.

pierpytom
  • 1,202
  • 1
  • 12
  • 25