Angular for循环中的承诺
Angular promise in a for loop
我有一个像这样的对象数组:
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"函数时已经"向前"了。
转发我的评论作为回答
相关文章:
- 等待循环调用的所有承诺完成
- 而循环使用蓝鸟承诺
- 蓝鸟承诺循环
- javascript承诺在循环中或如何逐个调用函数
- 循环中的承诺问题
- 转换嵌套'对于'循环成一个承诺,为了一个承诺?嵌套承诺
- 在循环中解析所有承诺后返回值
- 从 foreach 循环链接承诺
- 链接在webdriver.io中的while循环中承诺
- 循环超出范围,不执行承诺链
- 在nodejs中使用Q.js承诺进行循环的正确方法
- 如何仅从循环中调用最后的承诺
- 同时循环承诺,直到另一个承诺结束
- AngularJS:app.run() 中的承诺永远陷入循环
- 承诺:循环后执行
- 使用延迟和承诺循环ajax调用
- AngularJS承诺循环错误
- 节点承诺循环等待结果
- 如何在jquery中使用承诺循环
- Selenium WebdriverJS承诺循环