在异步回调中操作 redis 的一个异常
2014-09-01 · 549 chars · 3 min read
昨天在使用node redis的时候报了这样一个错:
TypeError: Object [object Object] has no method 'send_command'
at RedisClient.(anonymous function) (D:\index.js:991:25)
at null._onTimeout (D:\index.js:17:22)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
这个 bug 比较隐蔽,一步一步来看:
起因#
我要实现的是批量插入 redis 的列表(list),相关的 api 是这样的:client.rpush(key, [value1, value2, ..., callback]) ,参数必须一个一个列出来,要想批量添加(数组),只能使用apply 方法了:
var array = [
'list',
'1',
'2',
'3',
'4',
function () {
console.log('success')
},
]
client.rpush.apply(this, array)
数组的第一参数是 key,最后一个是回调函数,之间全部是要添加的数据。构造这样一个数组,使用apply 就很完美的解决了批量添加的问题。但是还是太年轻啊,执行 demo 的时候很正常,但是放入正式代码中就有问题了。
