Angular for循环中的承诺

Angular promise in a for loop

本文关键字:承诺 循环 for Angular      更新时间:2023-09-26

我有一个像这样的对象数组:

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

其中myArray[0].post.user = "joe"myArray[1].post.user = "bob"

我想添加另一个键(即comment)到post动态基于异步调用使用$resource,而通过数组循环。

远程Comments服务运行良好,看起来像这样:

.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 
    });
 }

为什么myArray.post.comments = comments抛出错误Cannot set property 'user' of undefined ?

我猜你的问题与C变量有关:也许你的C变量(在你的for循环中共享)在调用"then"函数时已经"向前"了。

转发我的评论作为回答