简体   繁体   中英

An angular promise that uses another promise?

I'm working on a user-authentication feature that works in two stages:

  • One HTTP (rest) call to get and confirm the user's identity
  • Followed by a call to a second system which will confirm the user's "roles" (permissions on the system).

I cannot do the second call until the first call is complete.

I have a service called UserService which has a function a bit like this:

UserService.load() # returns a promise which has when resolved gives the user's identity as a sring.

I want to also be able to do wrap it up so that I have:

RoleService.load() # returns a promise which when resolved gives the user's valid roles in the form ["role1", "role2", ... "roleN"]

In order to implement RoleService.load(), I imagine I'd have to do something like:

load: ()->
if promise?
  # Dont do anything if this promise is already cached
  promise
else
  promise = UserService.load().then((standardId)=>
    @set(@getRolesForUser(standardId))
  )

Which sort of works assuming that getRolesForUser(u) returns instantly. The problem is that this second call is also going to be on the network, so it would have to be turned into another promise.

What I really want to be able to do is chain the promises in such a way that having resolved the first promise, what I pass on to the next stage of the chain is the output of the second promise.

Can this be done? What's the syntax?

You can create a new defer and return his promise. Then when you have the value from the second call you can resolve the promise:

function load() {
  var deferred = $q.defer();
  UserService.load().then(function(standardId){
    getRolesForUser(standardId).then(function(val) {
      deferred.resolve(val)
    })
  });
  return deferred.promise;
}

Do something like, Wait for one to complete.

UserService.load()
.then(function(res){
      var id = res.data.id;
   RoleService.load()
   .then(function(role){
         var roleId = role.id;  // your logic
    })
});

Another better approach is to chain the promise.

UserService.load()
.then(function(res){
    var id = res.data.id;
    return RoleService.load();

})
.then(function(role){
         var roleId = role.id;  // your logic
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM