0

I'm not entirely sure how to look this up and I can't find anything on it when I look it up but in my controller I have these http.get calls:

$http.get("/getproducts.php", {transformResponse: []})
.success(function(data, status, headers, config) 
{
    try
    {
        $scope.products = JSON.parse(data);
        console.log("products call");
    }
    catch (e)
    {
        console.log(e, data);
    }
})
.error( function(data, status, headers, config) 
{
    console.log(data);
});

$http.get("/getdepartments.php", {transformResponse: []})
.success(function(data, status, headers, config) 
{
    try
    {
        $scope.departments = JSON.parse(data);
        console.log("department call");
    }
    catch (e)
    {
        console.log(e, data);
    }
})
.error( function(data, status, headers, config) 
{
    console.log(data);
});

$http.get("/getusers.php", {transformResponse: []})
.success(function(data, status, headers, config) 
{
    try
    {
        $scope.users = JSON.parse(data);

        for(var i = 0; i < $scope.products.length; i++)
        {

        }
    }
    catch (e)
    {
        console.log(e, data);
    }
})
.error( function(data, status, headers, config) 
{
    console.log(data);
});

Most of the time the http.get works and retrieves both products and departments which I can then use after retrieving the users. However, sometimes it retrieves the departments, retrieves the users and it tries to get into the for loop but it throws an error as it for some reason the $scope.products array is not populated. But after this error, the prompt for "products call" is then printed on the console meaning it does retrieve the data but sometimes the http.get for products is carried out after the others.

I don't fully understand why it does this.

J.Do
  • 303
  • 6
  • 26
  • 1
    Possible duplicate of [Asynchronous vs synchronous execution, what does it really mean?](https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean) Although _obviously_ not a direct duplicate, it will explain why your issue is happening, `$http.get` is asynchronous – George Nov 10 '17 at 15:51
  • You need to implement with a Promise. Specifically the use of Promise all. – Hoyen Nov 10 '17 at 15:53
  • Thanks for pointing me in the right direction! – J.Do Nov 10 '17 at 15:54
  • @J.Do It's no problem, it's better to understand why the issue is happening rather than someone just giving you the working code :) – George Nov 10 '17 at 15:55

0 Answers0