Is it possible in Angular.js to ensure that a given promise is resolved before another dependent promise?
Consider the following code snippet:
User.getAllUsers().then(function(users) {
$scope.users = users;
for (var i = 0; i < users.length; i++) {
console.log('username ' + users[i].username);
Message.getUnreadMessages(users[i].username, localStorage.getItem("token")).then(function(messages) {
console.log('username in second promise' + users[i].username);
$scope.messages.push(messages);
})
}
})
The services User
and Message
are being utilized here.
The first
console.log('username '+ users[i].username);
correctly displays the username of each user.
However, the second
console.log('username in second promise'+ users[i].username);
results in the error message:
Cannot read property 'username' of undefined