如何从AngularJS承诺链中的previous承诺访问结果如何呢? [英] How to access result from the previous promise in AngularJS promise chain?
问题描述
我有以下的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.
这篇关于如何从AngularJS承诺链中的previous承诺访问结果如何呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!