【问题标题】:Proper placement of callback with multiple async redis calls in node.js在 node.js 中使用多个异步 redis 调用正确放置回调
【发布时间】: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


    【解决方案1】:

    我认为最简单的方法是使用Multi 对象:

    that.Database.incr("id:jobs", function(id) { 
      var multi = that.Database.client.multi();
      multi.hmset('job:' + id, { ... });
      multi.rpush('jobs', id);
      multi.sadd('jobs.status.' + job.status, id);
      multi.sadd('jobs.name.' + job.name, id);
      multi.exec(cb);
      // or a bit less explicit:
      //
      // that.Database.client.multi()
      //                     .hmset('job:' + id, { ... })
      //                     .rpush('jobs', id)
      //                     .sadd('jobs.status.' + job.status, id)
      //                     .sadd('jobs.name.' + job.name, id)
      //                     .exec(cb);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 2020-04-13
      • 1970-01-01
      • 2017-03-20
      • 2020-06-04
      • 2020-04-09
      相关资源
      最近更新 更多