PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] how to set a timeout with node for redis request

 September 05, 2022     node.js, redis     No comments   

Issue

I've written a simple service using redis to store data in memory or fetch from disc and then store in memory. I'm trying to now control for rare cases where fetching to redis is slow. I've seen one example (https://gist.github.com/stockholmux/3a4b2d1480f27df8be67#file-timelimitedredis-js) which appears to solve this problem but I've had trouble implementing.

The linked implementation is:

/**
 * returns a function that acts like the Redis command indicated by cmd except that it will time out after a given number of milliseconds
 * 
 * @param {string} cmd The redis commmand to execute ('get','hset','sort', etc.)
 * @param {integer} timeLimit The number of milliseconds to wait until returning an error to the callback.
 * 
 */
function timeLimited(cmd, timeLimit) {
  return function() {
    var
      argsAsArr = Array.prototype.slice.call(arguments),
      cb        = argsAsArr.pop(),
      timeoutHandler;

    timeoutHandler = setTimeout(function(){
      cb(new Error('Redis timed out'));
      cb = function() {};
    }, timeLimit);

    argsAsArr.push(function(err, values){
      clearTimeout(timeoutHandler);
      cb(err,values);
    });

    client[cmd].apply(client,argsAsArr);
  };
}

however I don't understand how to implement this because client is never defined and the the redis key/value are never passed in. Could someone explain a little about how one could go about implementing this example? I've been searching for more information or a working example but not had any luck so far. Thank you.


Solution

This isn't very clearly written but when you call it with cmd (eg. SET, HSET, etc) and time limit it returns a function. You call this returned function with the values. I don't know where client comes from, I guess you need to have it in scope. This isn't very good code, I would suggest posting what you've written and asking how to achieve what you want with that.



Answered By - Matt
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing