TL;DR 如何从 getTTL 回调中获得返回值,以便在函数之外使用?
与Hubot和Redis一起学习咖啡记录,这里。我有一个函数没有返回我期望的值。这里的函数设计为获取Redis键的TTL并返回TTL值,例如4000 (秒)。这是我的咖啡记录:
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下面是用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;
}
});
};从coffeescript返回函数回调操作奇怪中,我理解了添加空return的必要性,但是我仍然没有收到回调回复中的值。如果我在Hubot中将该函数与响应对象集成,我可以执行msg.send reply,这样就可以很好地输出返回值。
但是,如果我将函数的返回值赋值给一个变量(例如ttl_val = getTTL "some-key" ),那么我只得到一个返回的布尔值(true),我假设它是getTTL函数本身的退出状态。所以,我的问题是:
我做错了什么,这使我无法在回调函数中接收应答值?在尝试提取值之前,我是否需要做一些类似如何等待coffeescript (或javascript)中的回调?的操作,以确保回调完成?
发布于 2014-12-16 20:44:24
您需要设置getTTL以接受它自己的回调函数:
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然后在你的大人物剧本里
robot.respond /what is the TTL for (.*)/i, (msg) ->
getTTL msg.match[1] msg.send编辑:要回答您的问题,编辑博士:您不能从回调中获取返回值。该值仅存在于回调函数的上下文中。您可以从回调函数中将该值赋值给某种全局变量,但这样您就永远不知道全局值何时被分配给它的值。
https://stackoverflow.com/questions/27513075
复制相似问题