0

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 []   
1
  • Can you create a jsFiddle.net example? Commented Aug 12, 2013 at 20:41

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The push is in the then block, so the push is working. The second log statement is not, so that log statement is happening before the then block is finishing. Your push is working correctly, you're just not logging it at the right place. If you put the log right after the addons.push it will show properly.
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.