lilbiscuit
lilbiscuit

Reputation: 2249

Angular promise in a for loop

I have an array of objects like this:

var  myArray = [{post:{message:"hi",user:"joe"}},{post:{message:"how are you",user:"bob"}}];

where myArray[0].post.user = "joe" and myArray[1].post.user = "bob"

I want to add another key (i.e. comment) to postdynamically based on an asynchronous call using $resource while looping through the array.

The remote Comments service works well and looks like this:

.factory('Comments',function($resource, myUrl) {
    var comments = $resource(myUrl + 'api/comments/:postId', {postId: '@id'});
    return comments;
})

in my controller

var  myArray = [{post:{message:"hi",user:"joe"}},{post:{message:"how are you",user:"bob"}}];

var messageCount = myArray.length;
var post_id = 1;   //comes from elsewhere

for (var c = 0; c < messageCount; c++) {

    Comments.get({postId:post_id}).$promise.then(function(comments) {
      console.log(comments);     //  <<---- objects appear to be fine in the console log
      myArray[c].post.comments = comments;  // <---- throws undefined error 

    });
 }

Why does myArray.post.comments = comments throw the error Cannot set property 'user' of undefined ??

Upvotes: 0

Views: 70

Answers (1)

illeb
illeb

Reputation: 2947

I guess your problem is related to the C variable: maybe your C variable (that is shared in your for loop) has gone "onward" when the "then" function is called.

repost of a my comment that served as answer

Upvotes: 1

Related Questions