Reputation: 3764
I've recently moved a lot of duplicate code into a common service that deals with retrieving a user's permissions efficiently. The concept is that when the service is instantiated, it will hit our identity server and retrieve the users permissions, storing them for some amount of time. Then subsequent calls by components to check permissions will use the cached data, so we don't have a ton of calls to our identity server delaying a user's experience.
I am loading permissions in the service's onInit method, with a flag set to whether or not it is done.
In that way, I can try to do something like this:
private isDataLoaded: boolean = false;
public userHasPermission(permissionName: string): boolean{
while(!this.isDataLoaded)
{
// Do something to wait/sleep synchronously for a second, then recheck
}
return userPermissions[permissionName] == true;
}
However, I cannot figure out how to get the thread to sleep synchronously. Every solution I look at is asynchronous, and uses a promise when the thread is finished....which doesn't work for this concept. How can I either sleep a
Upvotes: 1
Views: 170
Reputation: 1074809
I was hoping for the equivalent of .Result from C#. I want to be able to wait on the results in this call without having to set up the translation from promise to result in every place that calls this method
The way you do that in modern JavaScript (or TypeScript) is to use promises, but via async
/await
rather than the old clunky callback way.
private isDataLoaded: boolean = false;
public async userHasPermission(permissionName: string): Promise<boolean> {
// −−−−^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^−−−−−−−^
while(!this.isDataLoaded)
{
await /* the thing that does the load and returns a promise */;
// −−−−^^^^^
}
return userPermissions[permissionName] == true;
}
Code using it would also be in an async
function and do:
if (await userHasPermission("read")) {
// Read something...
}
The asynchronousness has to go all the way through the chain. Typically, at the entry point level (an event handler, for instance). Rejections automatically propagate (like errors in synchronous code) so there's nothing you need to do there, except that at the top level entry point (an event handler or similar) where you can't use an async
function (because nothing will use the promise it returns) you use .catch(error => { /*...handle/report error...*/ });
Upvotes: 1