如何从AngularJS承诺链中的previous承诺访问结果如何呢?结果、链中、AngularJS、previous

2023-09-13 04:51:13 作者:人不死终究会出头

我有以下的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
})

或本

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

或拨打第二个嵌套它们然后直接在 Task.all (这样我有用户通过闭合可用的对象)?嵌套他们正是我想避免的。

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.

推荐答案

您可以把又在哪里用户仍然可以访问的范围内(检查瓶盖)

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

从Kriskowal的 问: 本身文档,这两种风格是等价的。角的 $ Q 是根据问:

唯一的区别是嵌套。如果您需要在关闭捕获多个输入值这是筑巢的处理程序是有用的。

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