Recently, I have been transitioning to using the async await
pattern more frequently instead of the traditional Promise syntax because it can help in keeping the code structure cleaner. After some experimentation, I felt like I had a good grasp on how to utilize them effectively.
However, my confidence has now been shattered!
I have a function that returns a Promise...
private async checkSecurityTokenForNearExpiry(): Promise<boolean> {
const expiryOffset = 10;
try {
let existingToken = await this.userAuthorisationService.getSecurityToken();
if (existingToken != null && !existingToken.isTokenExpired(expiryOffset)) {
return true;
}
// Trying to obtain a new token.
this.logger.debug('checkSecurityTokenForNearExpiry requesting new token.');
this.getSecurityTokenWithRefreshToken().subscribe(obs => {
return true;
},
error => {
// Errors already logged
return false;
});
} catch (error) {
this.logger.error(`checkSecurityToken ${error}`);
return false;
}
}
This function calls another function that also returns a promise and involves an Observable, but everything seems fine with that setup.
Then, I call this function like this...
this.getDataStoreValues().then(async () => {
await this.checkSecurityTokenForNearExpiry(); // <-- not waiting
requestData(); // <-- this is called before checkSecurityTokenForNearExpiry returns
...
Within another Promise then
callback marked as async
(which should be correct), I am surprised to see that the call to
this.checkSecurityTokenForNearExpiry()
is not completing before requestData()
is invoked. I included the boolean
result from checkSecurityTokenForNearExpiry
just to test if returning something would make a difference, but unfortunately, it did not.
I'm at a loss here!
Could someone point out what I may be overlooking?
Thank you in advance!