adediran oladapo
adediran oladapo

Reputation: 89

AngularJS variable scope, JavaScript variable scope

var users = [];

Services.get(value).$loaded().then(function(data){

        users.push(data);
        // Taken data = [{name:"Jay",age:20}];
        console.log(users) // I get users = [{name:"Jay",age:20}]
});

console.log(users);

Hint: The function "Services" is getting it data from a web service.

// But I get an empty (users = []) for the second console.log, I guess the answer should be [{name:"Jay",age:20}] since I have use push in the function.Is it that the push function is not working. PLEASE HELP

Upvotes: 1

Views: 30

Answers (2)

Strelok
Strelok

Reputation: 51421

Your push is inside the then promise callback which runs when whatever $loaded does is finished.

Your first line of code runs immediately and returns that's why users is empty the first time.

Here is a cartoon to explain promises:

http://andyshora.com/promises-angularjs-explained-as-cartoon.html

Upvotes: 1

GPicazo
GPicazo

Reputation: 6676

The service's get method is asynchronous -- evident because it returns a promise object to which you chain a success callback to push the results of the get function into the user's array. Because asynchronous calls execute outside the normal flow, the second console.log is executed before the success callback.

The first callback is inside the success callback, so it gets executed until AFTER the get request completes and you push your user into the array, so that one should log the user in the array.

Upvotes: 0

Related Questions