Search code examples
typescriptpromiseasync-awaitmemoization

typescript async await operators promises and memoization pattern


I'm trying to modernize some of my code with latest TypeScript enhancements. We have a lot of memoization patterns in place. The idea is that some services have multiple subscribers and we want to make sure everybody waits on one call and doesn't fire multiple calls.
The code looks like that

private isAdmin: Promise<Boolean>;
public IsCurrentUserAdmin(): Promise<Boolean> {
if (!this.isAdmin) {
this.isAdmin = httpService.goGetTheData().then((data) => //do something and return Boolean);
}
return this.isAdmin;

My question is: will something like that have the same effect as with the await operator I "don't have access to the promise object" ?

public IsCurrentUserAdmin(): Promise<Boolean> {
const isAdminData = await httpService.goGetTheData();
// do something with the data to get the value
return isAdmin;
}

Solution

  • No, you absolutely need access to the promise object for the memoisation. async/await doesn't necessarily prevent that - it's just syntactic sugar for then calls - but in your particular case it doesn't really help. Since you're not caching the goGetTheData() promise, but the one returned by .then(…) (so that also the "do something" is executed just once), you would need to write an extra helper method for that:

    private isAdmin: Promise<boolean>;
    private async fetchIsAdmin(): Promise<boolean> {
        const data = await httpService.goGetTheData();
        // do something and
        return // a boolean
    }
    public IsCurrentUserAdmin(): Promise<boolean> {
        if (!this.isAdmin) {
            this.isAdmin = this.fetchIsAdmin();
        // you could `await this.isAdmin` in here as well, but that would happen for every call
        return this.isAdmin;
    }