Mohamed Hussain
Mohamed Hussain

Reputation: 7703

AngularJS Promise is executed before the data is fetched from Database

I am using angular Promise to execute the functions which are dependent on the data array fetched from the database.

I used resolve and promise to do that as below.

function Mainctrl($q,MyService){
    var defer=$q.defer();
    defer.promise
    //The data im receiving in promise is from the resolve "MyService.getAll({ID :ID})"
        .then(function(data){
            $scope.mydata=data;
            $scope.mylength=$scope.mydata.length;
            console.log();
        });
    //This code MyService.getAll({ID :ID}) returns an array from the database, i am using that result array in promise as "data"
    defer.resolve(MyService.getAll({ID :ID}));
}

Issue is promise is executed before the data array is populated always shows the lenght as 0. but i i use timeout instead of promise, data array is populated and length is shown correctly.

MyFactory method getAll is

app.factory("MyService", function($resource, $http) {
  var resource = $resource("/rest/:ID ", { ID : "@_ID " },
    {
      'create':  { method: 'POST' },
      'getAll':   { method: 'GET', isArray: true },
      'get':    { method: 'GET', isArray: false },
      'update':  { method: 'PUT' },
      'destroy': { method: 'DELETE' }
    }
  );
  return resource;
});

Upvotes: 0

Views: 591

Answers (2)

Chandermani
Chandermani

Reputation: 42669

I am not sure what you have done, but controller does not require to create any defer\promise object.

The code should be in lines of

function Mainctrl($scope,MyService){
        MyService.getAll({ID :ID}).then(function(data){
            $scope.mydata=data;
            $scope.mylength=$scope.mydata.length;
            console.log();
        });
}

Update Since you service is not returning promise but a resource object the call to getAll does not return promise but an array that gets filled later.

function Mainctrl($scope,MyService){
            MyService.getAll({ID :ID},function(data){
                $scope.mydata=data;
                $scope.mylength=$scope.mydata.length;
                console.log();
            });
    }

Upvotes: 4

Bergi
Bergi

Reputation: 664650

According to docs.angularjs.org/api/ngResource.$resource, the getAll method does return an empty array which will be populated asynchronously with values when they arrive. Ugly design.

function Mainctrl($scope,MyService){
    MyService.getAll({ID :ID}).$promise.then(function(data){
        $scope.mydata = data;
        $scope.mylength = data.length;
    });
}

Upvotes: 1

Related Questions