尝试使用async.concat从redis检索数据时出错

时间:2011-08-10 06:42:23

标签: asynchronous node.js redis

我正在关注异步作者here发布的示例,但我收到了错误。

  • redis的-2.2.12
  • node v0.4.11-pre

这是我的代码:

var async = require('async');
var redis = require('redis');

var keys = ['key1', 'key2', 'key3'];

var client = redis.createClient();
var multi = client.multi();
for (var key in keys) {
  multi.hmset(key, {'some': 'value'});
}
multi.exec(function(err, res) {
  if (err) throw err;
  console.dir(res);

  var myCallback = function(err, res) {
    console.log('in myCallback');
    console.dir(res);
    client.quit();
    process.exit();
  };
 async.concat(keys, client.hgetall, myCallback);
});

产生以下输出:

$ node redis_test.js
[ 'OK', 'OK', 'OK' ]

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
TypeError: Object #<Object> has no method 'send_command'
    at /home/project/node_modules/redis/index.js:666:25
    at /home/project/node_modules/async/lib/async.js:508:13
    at /home/project/node_modules/async/lib/async.js:97:13
    at Array.forEach (native)
    at /home/project/node_modules/async/lib/async.js:26:24
    at /home/project/node_modules/async/lib/async.js:96:9
    at /home/project/node_modules/async/lib/async.js:507:9
    at Object.concat (/home/project/node_modules/async/lib/async.js:141:23)
    at /home/project/redis_test.js:21:9
    at Command.callback (/home/project/node_modules/redis/index.js:827:13)

1 个答案:

答案 0 :(得分:4)

当异步运行client.hgetall时,它会在this内删除hgetall的值。您可以将一个匿名函数包装在一起,或者使用fn.bind(),如下所示。

您还希望避免使用for .. in迭代数组。使用常规for循环或arr.forEach()。你的例子会因为书面而神秘失败。这是一个似乎可以做你想要的版本:

var async = require('async');
var redis = require('redis');
var keys = ['key1', 'key2', 'key3'];

var client = redis.createClient();
var multi = client.multi();
keys.forEach(function (key) {
  multi.hmset(key, {'some': 'value'});
});
multi.exec(function(err, res) {
  if (err) throw err;
  console.dir(res);

  var myCallback = function(err, res) {
    console.log('in myCallback');
    console.dir(res);
    client.quit();
    process.exit();
  };
 async.concat(keys, client.hgetall.bind(client), myCallback);
});

输出:

[ 'OK', 'OK', 'OK' ]
in myCallback
[ { some: 'value' },
  { some: 'value' },
  { some: 'value' } ]

要调试神秘故障,您可以在发送任何Redis命令之前通过node_redis打开redis.debug_mode = true;中的调试日志记录。