1

TL;DR如何从client.ttl回调中获取返回值以在getTTL函数外使用?

在这里使用 Hubot 和 Redis 学习 Coffeescript。我有一个函数没有返回我期望的值。此处的函数旨在获取 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;
    }
  });
};

咖啡脚本返回函数回调行为奇怪,我了解需要添加空return,但我仍然没有收到回调回复中的值。如果我将该函数与Hubot 中的Response 对象msg.send reply集成,我可以这样做,并且可以很好地输出返回值。

但是,如果我将函数的返回值分配给一个变量,例如ttl_val = getTTL "some-key",那么我只会得到一个返回的布尔值 ( true),我假设它是getTTL函数本身的退出状态。所以,我的问题是:

我做错了什么导致我无法在回调函数中接收回复值?我是否需要做类似如何等待咖啡脚本(或javascript)中的回调?确保我的回调在尝试拉取值之前完成?

4

1 回答 1

0

您需要设置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

然后在你的hubot脚本中

robot.respond /what is the TTL for (.*)/i, (msg) ->
    getTTL msg.match[1] msg.send

编辑:回答你是tl;博士编辑:你不能从回调中获取返回值。该值仅存在于回调函数的上下文中。您总是可以从回调函数内部将该值分配给某种全局变量,但是您永远不会知道该全局值何时被分配了它的值。

于 2014-12-16T20:44:24.033 回答