redis / node-redis

Redis Node.js client
https://redis.js.org/
MIT License
16.92k stars 1.89k forks source link

accessing cache inside a promise is not working ok #1539

Open vandanachadha opened 4 years ago

vandanachadha commented 4 years ago

Issue

I am doing the following inside a function which is called as a promise: let cachedData = await init(redisKey); if(cachedData){ logger.info("FOUND CACHED MENUDATA..."); return cachedData; } else { logger.info("NOTFOUND CACHED MENUDATA...", venueId); }

However the control always comes to the else and prints "NOT FOUND CACHED MENUDATA". After that it prints logs inside the redis.readCache function.

const init = async(redisKey) => { const cachedData = await redis.readCache(redisKey); console.log(Hi CACHED DATA GOT,cachedData); return cachedData; };


Environment

ljluestc commented 3 months ago
const redis = require('redis');
const { promisify } = require('util');
const client = redis.createClient();
const getAsync = promisify(client.get).bind(client);

const logger = {
  info: console.log,
};

// Function to read cache data
const readCache = async (key) => {
  try {
    const data = await getAsync(key);
    if (data) {
      logger.info(`Hi CACHED DATA GOT: ${data}`);
      return JSON.parse(data); // Assuming cached data is in JSON format
    }
    return null;
  } catch (error) {
    logger.info('Error reading cache:', error);
    return null;
  }
};

// Function to initialize and fetch cached data
const init = async (redisKey) => {
  const cachedData = await readCache(redisKey);
  return cachedData;
};

// Main function where init is called
const mainFunction = async (redisKey, venueId) => {
  const cachedData = await init(redisKey);
  if (cachedData) {
    logger.info("FOUND CACHED MENUDATA...");
    return cachedData;
  } else {
    logger.info("NOT FOUND CACHED MENUDATA...", venueId);
    // Handle the case where cached data is not found
    // Fetch fresh data, process, and cache it if needed
  }
};

// Example usage
const redisKey = 'some-redis-key';
const venueId = 'some-venue-id';

mainFunction(redisKey, venueId);