Using lb-services count servcie in angular

102 Views Asked by At

I am using below code in my angular using lbservices, I want to get value of count, but I instead of output as a1=8 and a2=8, I am getting result as a1=8 and a2=2,

var getOrganisationCount = function () {
                var count = 2;
                var query = {};
                Organisation
                    .count()
                    .$promise
                    .then(function (response) {
                        count = response.count;
                        console.log('a1===' + count);
                    });
                console.log('a2=' + count);
            };
            getOrganisationCount();
2

There are 2 best solutions below

0
On BEST ANSWER

Your getOrganisationCount function is making a network call to Organisation model that you have in your application.This network call Organisation.count().$promise is an async call and the code inside then block will be executed once you get a response from the server, ie: when the async operation is finished.

But the code console.log('a2=' + count) is not inside then block and it will be executed before the response comes from your server. Since the value of count is 2 initially, you get the output as 2 while the second console statement runs after the response, its value gets updated and you get the output as 8.

If you run your code you will see that console.log('a2=' + count) is ouput first then console.log('a1===' + count) which is a proof to what I explained above.

If you want to understand more about how asynchronous function works, you can go through this well described SO answer.

1
On

Because a1 value is printed once the response from the async call is recieved, whereas a2 is printed immediately.

Code inside then callback is called when the server response has been recieved, whereas other code executes sequentially.

Update: Since you are working with promise, you should return promise from the function call, which the caller can then resolve.

var getOrganisationCount = function() {
  var count = 2;
  var query = {};
  return Organisation
    .count()
    .$promise
    .then(function(response) {
      count = response.count;
      console.log('a1===' + count);
      return count;
    });
};
getOrganisationCount().then(function(count) {
  console.log('a2=' + count);
});

Make note how the function now returns a promise instead of count