0

I have a nested promises and one promise depends on the result of the other so is it possible to force Angular.js to solve a gien promise before solving the second.

Here is my code:

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

User and Message are both services. The console.log('username '+ users[i].username);displays the correct username. The console.log('username in second promise'+ users[i].username);throws the error`:

Cannot read property 'username' of undefined

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
juliana Morales
  • 177
  • 3
  • 3
  • 10

1 Answers1

1

Try this:

User.getAllUsers().then(function(users) {
    $scope.users = users;
    for (var i = 0; i < users.length; i++) {
      (function(user){
        console.log('username ' + user.username);
        Message.getUnreadMessages(user.username, localStorage.getItem("token")).then(function(messages) {
            console.log('username in second promise' + user.username);
            $scope.messages.push(messages);
        })
      })(users[i]);
    }
})

See https://developer.mozilla.org/en/docs/Web/JavaScript/Closures, chapter about Closure and loop.

Thierry
  • 5,133
  • 3
  • 25
  • 30