'How to prevent data from being loaded multiple times in a row with Redis in JavaScript

I understand that running JavaScript in node is single threaded (which is were I'm running the below code), but am worried that the await func(...) call in the below call will pause execution while it gets data, causing the next call to come into this method and call the func(...) again.

If I was doing this in C# or Java I'd use a lock to make sure that the thread waits before proceeding. Should I be doing something similar in JavaScript?

export async function getCacheData(
  cacheKeyBase: String,
  func: any,
  args: any,
  context: any,
  timeOut: any = IOREDIS_SLOW_TIME_OUT,
) {
  const cacheKey = `${cacheKeyBase}-${JSON.stringify(args)}`;
  const cacheData = REDIS_ENABLED ? await redis.get(cacheKey) : undefined;
  let retData;
  if (cacheData) {
    retData = JSON.parse(cacheData);
  } else {
    retData = await func(args, context);
    await redis.set(cacheKey, JSON.stringify(retData), 'ex', timeOut);
  }
  return retData;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source