Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access result from the previous promise in AngularJS promise chain? [duplicate]

I have the following code:

authService.authenticate()
.then(function (user) {
  return Task.all({user: user})
})
.then(function (tasks) {
  // How to access user object here?
})

Is there some built-in way to pass user object to the second then function without doing something like this:

var user2 = null;
authService.authenticate()
.then(function (user) {
  user2 = user
  return Task.all({user: user})
})
.then(function (tasks) {
   // Use user2 here
})

or this:

authService.authenticate()
.then(function (user) {
  var defer = $q.defer()
  Task.all({user: user}).then(function (tasks) {
    return defer.resolve(user, tasks)
  })
  return defer.promise
})
.then(function (user, tasks) {
   // Use user2 here
})

or nesting them by calling the second then directly on Task.all (this way I'd have user object available via closure)? Nesting them is exactly what I'm trying to avoid.

like image 611
szimek Avatar asked Oct 21 '22 20:10

szimek


1 Answers

You can put the then within the scope where user is still accessible (check closures)

authService.authenticate()
.then(function (user) {
  Task.all({user: user})
  .then(function (tasks) {
    // How to access user object here?
  })
})

From Kriskowal's Q documentation itself, both styles are equivalent. Angular's $q is based on Q

The only difference is nesting. It’s useful to nest handlers if you need to capture multiple input values in your closure.

like image 77
kumarharsh Avatar answered Oct 27 '22 10:10

kumarharsh