Javascript 填充缓存数据

Javascript 填充缓存数据,javascript,Javascript,考虑以下javascript中的查询缓存函数 channelCache={}; async getChannelType(channel: string): Promise<string> { if (!this.channelCache.hasOwnProperty(channel)) { channelCache[channel] = await this._deviceService.GetChannelSetting(channel); }

考虑以下javascript中的查询缓存函数

channelCache={};
async getChannelType(channel: string): Promise<string> {
    if (!this.channelCache.hasOwnProperty(channel)) {
         channelCache[channel] = await this._deviceService.GetChannelSetting(channel);
     }
     return channelCache[channel];
}
channelCache={};
异步getChannelType(通道:字符串):承诺{
如果(!this.channelCache.hasOwnProperty(通道)){
channelCache[channel]=等待此操作。\u deviceService.GetChannelSetting(通道);
}
返回channelCache[channel];
}
这很好,但是在我的代码中有一个场景,一个接一个地调用了100次。问题是所有100次都通过了if语句并开始查询服务。如果if语句周围有某种互斥机制,一次只允许运行一个查询,那么我会喜欢它


我试过prex信号量,但在IE11中似乎不起作用。有什么建议吗?

您不需要任何类型的信号量或锁定

相反,您应该缓存异步承诺,而不是最终值:

getChannelType(channel: string): Promise<string> {
    if (!this.channelCache.hasOwnProperty(channel)) {
         channelCache[channel] = this._deviceService.GetChannelSetting(channel);
     }
     return channelCache[channel];
}
getChannelType(通道:字符串):承诺{
如果(!this.channelCache.hasOwnProperty(通道)){
channelCache[channel]=此._deviceService.GetChannelSetting(通道);
}
返回channelCache[channel];
}

谢谢你的建议。你迫使我重新思考我的缓存机制,结果它工作得很好。