0

My script has a function that login the user as follows:

class myClient {
    SignIn() {
            this._userManager.signinRedirect();      

            this._userManager.processSigninResponse().then(function (response) {               

                manager._userManager.getUser().then(function (user) {
                    manager._loggedUser = user;
                });        
            })
        }
}

As you can see, there are two nested promises. The user is only logged into the system once the inner most promise is resolved (i.e.: manager._loggedUser = user)

Now, I would like my class to expose just two methods: SignIn() [as described above] and GetUserInfo():

GetUserInfo() {
     // ...
    return this._loggedUser;
}; 

So that anyone using my class would just need to follow these steps in order to get the logged in user profile:

  1. create the object
  2. call the signin method
  3. get the user info

How can i 'synchronize' the 2nd and the 3rd step, in order to ensure that the _loggedUser is not null after calling the signin() method first and the GetUserInfo() after?

alessalessio
  • 1,224
  • 1
  • 15
  • 28

1 Answers1

0

It should be flattened to avoid 'callback hell' (one of the reasons why promises are used) - unless there are reasons to not do that (i.e. when response is used in nested promises). And it should return a promise.

SignIn() {
  this._userManager.signinRedirect();      

  return this._userManager.processSigninResponse().then(function (response) {               
    return manager._userManager.getUser();
  })
  .then(function (user) {
    manager._loggedUser = user;
  });        
}

Considering that GetUserInfo relies on SignIn results, promises should be utilized when using them together.

obj.SignIn().then(() => {
  const info = obj.GetUserInfo();
  ...
});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565