so have function need combine multiple promises responses, after reading realized promises async in case loop going complete before responses do. should need use $q.all in case? how can improve piece of code? thanks..
$scope.messages = []; function getpastmessages(data) { angular.foreach(data, function(item) { message.get(item.id).then(function(msg) { if (msg.data.is_private === false) { user.getpictures(msg.data.user.id).then(function(pics) { msg.data.user.pictures = pics.data; }); } else { user.get(msg.data.im.sender).then(function(sender) { msg.data.im.sender = sender.data; user.get(msg.data.im.reciever).then(function(reciever) { msg.data.im.reciever = reciever.data; }); }); } console.log(msg.data); // show 4 objects correct $scope.messages.push(msg.data); console.log($scope.messages); // show array of 6 objects ???????? }) }); };
without working example difficult understand context of code, can similar this.
the basic idea create list of promises need wait for. each of promises within list should return result (presumably msg.data
). using $q.all
, you'll list of results (one each promise) @ end. note things returned within .then
wrapped in promises if aren't promises.
$scope.messages = []; function getpastmessages(data) { var promises = []; angular.foreach(data, function(item) { promises.push(getmessage(item)); }); return $q.all(promises); } function getmessage(item) { return message.get(item.id).then(function(msg) { if (msg.data.is_private === false) { return user.getpictures(msg.data.user.id).then(function(pics) { msg.data.user.pictures = pics.data; return msg.data; }); } else { return user.get(msg.data.im.sender).then(function(sender) { msg.data.im.sender = sender.data; return user.get(msg.data.im.reciever).then(function(reciever) { msg.data.im.reciever = reciever.data; return msg.data; }); }); } }); }
usage:
getpastmessages(data).then(function(results) { (var = 0; < results.length; i++) { $scope.messages.push(results[i]); } });