开发者

Error when trying to use async.concat to retrieve data from redis

I was following an example posted by the async author here but I'm getting an error.

  • redis-2.2.12
  • node v0.4.11-pre

Here's my code:

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);
});

Produces the following output:

$ node redis_test.js
[ 'OK', 'OK', 'OK' 开发者_C百科]

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)


When async runs client.hgetall, it trashes the value of this inside of hgetall. You can either wrap up an anonymous function to glue this together, or use fn.bind() as shown below.

You also want to avoid using for .. in to iterate over an Array. Use either a regular for loop or arr.forEach(). Your example would have mysteriously failed as written. Here's a version that seems to do what you want:

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);
});

This outputs:

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

To debug the mysterious failure, you can turn on debug logging in node_redis by doing redis.debug_mode = true; before sending any Redis commands.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜