简体   繁体   中英

Populating Cached Data

Consider the following caching on query function in javascript

channelCache={};
async getChannelType(channel: string): Promise<string> {
    if (!this.channelCache.hasOwnProperty(channel)) {
         channelCache[channel] = await this._deviceService.GetChannelSetting(channel);
     }
     return channelCache[channel];
}

This works well however there is a scenario in my code where this is called 100 times one after another. The issue is that all 100 times gets past the if statement and starts querying the service. What I'd like if some sort of mutex mechanism around the if statement that will only allow 1 query to run at a time.

I've tried prex semaphore but it looks like this does not work in IE 11. Any suggestions?

You don't need any kind of semaphores or locking.

Instead, you should cache your async promise instead of the final value:

getChannelType(channel: string): Promise<string> {
    if (!this.channelCache.hasOwnProperty(channel)) {
         channelCache[channel] = this._deviceService.GetChannelSetting(channel);
     }
     return channelCache[channel];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM