There is a user service in which work with the backend for authorization, registration, and so on is implemented.

The algorithm is as follows:

There is a method for obtaining a token from the LAN:

getToken() { this.token = this.storageService.get('token'); return true; }; 

And checking this token on the server side:

 tokenVerify() { return this.http.post(this.verifyUrl, JSON.stringify({ token: this.token, } ),{headers: this.headers}) .toPromise() .then(response => { if(response.json().token == this.token) { this.headers.append('authorization', `JWT ${this.token}`); } }) .catch(this.handleError); }; 

In case of successful verification, the token will be included in all request headers.

As well as the authorization verification method

 checkAuth() { if (this.getToken() && this.tokenVerify()) { return true; } else return false }; 

+ There is a method to get a username through a token

 getMyUserName(): Promise<ICatalogUser> { console.log('Получаем имя'); console.log(this.headers); return this.http.get(this.meUrl, {headers: this.headers}) .toPromise() .then(response => response.json() as ICatalogUser) .catch(this.handleError); }; 

The main problem is that the verification method of the token is asynchronous and the method for obtaining the name is asynchronous and when I try to verify the authorization in the component and get the user name, nothing happens because there is no token yet during the verification:

 ngOnInit(): void { this.getPosts(); this.checkAuth(); this.user = this.userService.me; } 

Please tell me how best to solve this problem?

Reported as a duplicate at Grundy. javascript Jan 1 '17 at 14:14 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    If the method is needed synchronous, then instead of functions, enter the flags currentToken and tokenVerified , then set them during initialization and check in any combinations. If they are displayed in $scope , the interface will be able to respond accordingly. If you need asynchronous, then Promise.all , for example.

      I would suggest using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then "Promise chaining" more actively, when you give what you need for the next through return and then use it, then the synchronous && turn into a chain of asynchronous then (). then ()

      Another well-written: http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/