Javascript 使用另一个承诺的有棱角的承诺?
我正在开发一个分两个阶段工作的用户身份验证功能:Javascript 使用另一个承诺的有棱角的承诺?,javascript,angularjs,coffeescript,Javascript,Angularjs,Coffeescript,我正在开发一个分两个阶段工作的用户身份验证功能: 一个HTTP(rest)调用以获取并确认用户的身份 然后调用第二个系统,该系统将确认用户的“角色”(对系统的权限) 在第一次呼叫完成之前,我无法进行第二次呼叫 UserService.load() .then(function(res){ var id = res.data.id; RoleService.load() .then(function(role){ var roleId = role.i
- 一个HTTP(rest)调用以获取并确认用户的身份
- 然后调用第二个系统,该系统将确认用户的“角色”(对系统的权限)
UserService.load()
.then(function(res){
var id = res.data.id;
RoleService.load()
.then(function(role){
var roleId = role.id; // your logic
})
});
我有一个名为UserService的服务,它的功能有点像这样:
UserService.load() # returns a promise which has when resolved gives the user's identity as a sring.
我还希望能够将其打包,以便:
RoleService.load() # returns a promise which when resolved gives the user's valid roles in the form ["role1", "role2", ... "roleN"]
为了实现RoleService.load(),我想我必须执行以下操作:
load: ()->
if promise?
# Dont do anything if this promise is already cached
promise
else
promise = UserService.load().then((standardId)=>
@set(@getRolesForUser(standardId))
)
假设getRolesForUser(u)立即返回,哪种方法有效。问题是,这第二个电话也将在网络上,所以它必须变成另一个承诺
我真正想做的是以这样一种方式将承诺链接起来,即在解决了第一个承诺之后,我将传递给下一个阶段的是第二个承诺的输出
这能做到吗?语法是什么?您可以创建一个新的延迟并返回他的承诺。 然后,当您从第二次通话中获得价值时,您可以解决承诺:
function load() {
var deferred = $q.defer();
UserService.load().then(function(standardId){
getRolesForUser(standardId).then(function(val) {
deferred.resolve(val)
})
});
return deferred.promise;
}
像这样做,
等待一个完成
UserService.load()
.then(function(res){
var id = res.data.id;
RoleService.load()
.then(function(role){
var roleId = role.id; // your logic
})
});
另一个更好的方法是将承诺连成链条
UserService.load()
.then(function(res){
var id = res.data.id;
return RoleService.load();
})
.then(function(role){
var roleId = role.id; // your logic
});