suncoastkid
suncoastkid

Reputation: 2223

Javascript array push is not working

I am stuck on why this array push will not work... any help appreciated.

    var addons = new Array();

    myService.addon_dependencies(arr[i]['addoncode']).then(function(dependency) {
        console.log(dependency[0].addon_depend);  //returns A6002
        addons.push(dependency[0].addon_depend);
    });

    console.log(addons); //returns []   

Upvotes: 0

Views: 2330

Answers (3)

Remigius Kijok
Remigius Kijok

Reputation: 225

console.log(addons) is executed before the item is beeing pushed into the array. So you see the empty array. Try the console.log after you push new items into it.

Upvotes: 0

Jeff Storey
Jeff Storey

Reputation: 57192

This is because the addon_dependencies method is not finishing before you run console.log. The then method shows you're probably using some sort of promise framework. If you print it out in the then block it should work.

Upvotes: 5

Aegis
Aegis

Reputation: 1789

Array.push is working; your code must be executed asynchronously, hence the empty addons.

Upvotes: 1

Related Questions