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();
Your
getOrganisationCount
function is making a network call to Organisation model that you have in your application.This network callOrganisation.count().$promise
is an async call and the code insidethen
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 insidethen
block and it will be executed before the response comes from your server. Since the value ofcount
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 thenconsole.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.