您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在异步回调中操作redis的一个异常

2025/7/31 12:08:13发布21次查看
昨天在使用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]
昨天在使用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的时候很正常,但是放入正式代码中就有问题了。
解决
正式代码的数据一般是异步得到的,用settimeout 模拟一下:
var redis = require('redis'), client = redis.createclient(6379, '127.0.0.1', { auth_pass: 'home.local.17173.com' });client.on('error', function(err) { console.log('redis错误:' + err);});client.on('connect', function() { settimeout(function() { var array = ['list', '1', '2', '3', '4', function() { console.log('success'); } ]; client.rpush.apply(this, array); }, 1000);});
执行上面的代码会报出文章开头的错误,提示“object [object object] has no method ‘send_command’”,联系到apply 的this,问题可能出在作用域上,修改倒数第三行代码:
client.rpush.apply(client, array);
执行后就ok了:
所以问题就是出在作用域上,apply 这样的比较明显,但是使用async等就不是那么明显了。在stackoverflow上找到一个问题,有bug的代码是这样的:
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);});
错误还是和文章开头的一样,解决方法是使用bind 函数。修改倒数第二行代码如下:
async.concat(keys, client.hgetall.bind(client), mycallback);
bind函数可以用来设置this 参数,具体用法看这里。
原文地址:在异步回调中操作redis的一个异常, 感谢原作者分享。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product