TL;DR How can I get the return value out of the client.ttl
callback for use outside of the getTTL
function?
Learning Coffeescript with Hubot and Redis, here. I've got a function that's not returning the value I expect it to. The function here is designed to get the TTL for a Redis key and return the TTL value, eg 4000 (seconds). Here's my Coffeescript:
getTTL = (key) ->
client.ttl key, (err, reply) ->
if err
throw err
else if reply in [-1, -2]
"No TTL or key doesn't exist."
else
reply
return
Now here is it compiled in JS:
var getTTL;
getTTL = function(key) {
client.ttl(key, function(err, reply) {
if (err) {
throw err;
} else if (reply === (-1) || reply === (-2)) {
return "No TTL or key doesn't exist.";
} else {
return reply;
}
});
};
From coffeescript return function callback acting strange , I understand the need to add the empty return
, but I'm still not receiving the value in the callback reply. If I integrate the function with the Response object in Hubot, I can do msg.send reply
and that works just fine to output the return value.
However, if I assign the return value of the function to a variable, eg ttl_val = getTTL "some-key"
, then I only get a boolean value returned ( true
), which I'm assuming is the exit status of the getTTL
function itself. So, my question is:
What am I doing wrong that's preventing me from receiving the reply value in the callback function? Do I need to do something like How do I wait for a callback in coffeescript (or javascript)? to ensure that my callback completes before trying to yank the value?
You need to setup getTTL
to accept its own callback function:
getTTL = (key, done = ()->) ->
client.ttl key, (err, reply) ->
if err
throw err
else if reply in [-1, -2]
done "No TTL or key doesn't exist."
else
done reply
Then in your hubot script
robot.respond /what is the TTL for (.*)/i, (msg) ->
getTTL msg.match[1] msg.send
Edit : To answer you're tl;dr edit: you cannot get the return value out of the callback. That value only exists in the context of the callback function. You can always assign that value to some kind of global variable from inside the callback function, but then you'll never know when that global value got assigned its value.
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.