【发布时间】:2014-01-30 04:06:27
【问题描述】:
我正在使用 node.js 和 redis 构建一个作业队列系统,并试图弄清楚如何最好地在这个函数中实现回调。
在代码中我调用了 3 次 cb() 只是为了强调我正在谈论的 redis 调用。
显然我可以只嵌套三个调用 (rpush -> sadd -> sadd),但鉴于它们不相互依赖,这样就违背了异步处理的目的,不是吗?
Queue.prototype.pushJob = function(job, cb) {
var that = this;
cb = cb || function(err, res) {};
if (job.name) {
that.Database.incr("id:jobs", function(id) { //Increment redis variable id:jobs
that.Database.client.hmset('job:' + id, { //Callback of incr, set the hash of job:incr
"name": job.name,
"status": job.status,
"payload": job.payload,
"priority": job.priority
}, function() { //Callback of hmset, add incr to jobs list
that.Database.client.rpush('jobs', id, function(err, res) { //Add id to jobs array
cb(err, res); //Callback
});
that.Database.client.sadd('jobs.status.' + job.status, id, function(err, res) { //Add status to type array
cb(err, res); //Callback
});
that.Database.client.sadd('jobs.name.' + job.name, id, function(err, res) { //Add status to type array
cb(err, res); //Callback
});
});
});
return true;
}
console.log("Invalid data passed to Job");
cb(null);
return false;
};
归根结底,这是我第一次使用 redis,我仍在努力思考它的一些功能。
为了让 hmset、rpush 和 sadd 函数知道它们要推送到哪个 ID,它们必须在 incr 调用的回调中,但在那之后,我不确定什么是构建的最佳方式我的代码是。任何帮助将不胜感激!
【问题讨论】:
标签: javascript node.js asynchronous redis