0

function getTotal.getValues() is a server call that returns "one", "two", "three" ... "nine". i can print them with console.log(res). however, it seems i cannot push them into variable v created inside runTest Function. in this code, console.log(r) does not print anything because return v is empty. any ideas?

var test = [1,2,3,4,5,6,7,8,9];

        function runTest(val) {
            var v = [];
            val.forEach(function(t) {
                getTotal.getValues(t).then(function(res) {
                    //console.log(res);
                    v.push(res);
                });
            });
            return v;
        }
        runTest(test).forEach(function(r) {
            console.log(r);
        });
5
  • Your syntax looks fine to me. Are you sure it's a syntax error you're getting? Commented Aug 6, 2014 at 16:54
  • yes, i'm still getting the same error. syntax error, $injector could not initiate ... Commented Aug 6, 2014 at 17:19
  • If it was a syntax error, it would be saying something like SyntaxError: Unexpected token. The code above cannot be producing the error you're reporting. Commented Aug 6, 2014 at 17:21
  • ok Mike, this i was setting my test variable in a function out side of my controller, then returning the result and grabbing it inside controller, syntax error is gone. i have another problem, let me update my question ... Commented Aug 6, 2014 at 17:28
  • I have edited the question after your hint, this is where i mean by foreach does not work. v.push(res) seems to be not working, however i can print res values with console.log(res) Commented Aug 6, 2014 at 17:38

2 Answers 2

1

Are you mistaken between angular forEach and javascript forEach.

Angular forEach should be like this. I can't see angular forEach I your code snippet.

angular.forEach(test, function(value, key) {
    console.log(value);
});
Sign up to request clarification or add additional context in comments.

Comments

0

This is how your forEach function should look like:

var test = [1,2,3,4,5,6,7,8,9];
test.forEach(function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
});
// logs:
// a[0] = 1
// a[1] = 2
// a[2] = 3

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

But if you want to use angular.forEach(), refer to: https://docs.angularjs.org/api/ng/function/angular.forEach

Good luck!

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.