aync 中的 node.js redis 选择和成员

标签 node.js asynchronous redis

我对 node.js 中的异步调用感到很痛苦。我知道我必须享受它,但实际上我讨厌它,因为 node.js 强制你使用它,而且没有其他选择。

我尝试在不同的数据库上运行 smembers。所以在这里我想确保我使用了所有 3 个数据库,因此我使用 _.after。但是它不起作用。

var redisfetcher = function(string, callback1)
{
   var retrieved = []

    var callback = function(){
        callback1(retrieved)
    }

    var afterAll = _.after(3,callback)

    for (var col=0; col<=2; ++col) {
        client.select(col, function() {
            client.smembers(string, function (err, replies) {
             if(!err){
                retrieved.push(replies)
                }
            })
        afterAll();
        })
    }

redisfetcher("offer", function(returnValue) {
    console.log(returnValue)
    })

如果你能帮助我,我将不胜感激。

如果您能展示如何在同步模式下运行以下代码,我将不胜感激。

最佳答案

使用async模块。

var async = require('async');

async.mapSeries([0, 1, 2], function (db, done) {
    // Here `db` will be `0`, or `1` or `2`, i.e. each element of the array.
    // The `done` is an internal callback used by the `async` module
    // to track whether a particular element of the array is completed
    // to be processed. When you're "done" consuming the `db` element of the
    // array, you must call `done` to indicate that `async` can now give you
    // yet another element to consume, if there is any left to process.
    // When all elements are processed, `async` calls the final function
    // passes to it as the last argument. For more information refer to
    // very detailed docs of `async` module at 
    // https://github.com/caolan/async#mapSeries.
    async.waterfall([
        function (cb) {
            client.select(db, cb);
        },
        function (cb) {
            client.smembers(string, cb);
        }
    ], done);
}, function(err, resultArr) {
    err && console.trace(err);

    // `resultArr` now contains 3 replies.
});

请注意上面的代码调用 mapSeries 是顺序的(不要与同步混淆),而不是并行的,这与 map 不同。我建议在您的情况下为每个数据库使用不同的 Redis 连接,因为如果并行调用,例如异步调用可能会由于选择不同的数据库而发生冲突。这可能会导致针对同一数据库而不是预期的不同数据库运行命令。如果您对同一个数据库运行多个命令,则单个连接就可以。

对于连接池,使用 node-pool .

关于aync 中的 node.js redis 选择和成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25760682/

相关文章:

c# - 如何为 WebClient.DownloadFileAsync 捕获 404 WebException

redis - 在 Redis 中设置计数器的预定义范围

javascript - 如何使用 Node js 从 firebase 数据库以 JSON 格式检索所需的 JSON 对象

java - 架构该如何走?

javascript - Node.js 什么时候使用异步有意义?

java - Spring 4在异步任务完成时更改jsp

html - 使用每行具有多个元素的 Jade/Express.js 渲染表格

node.js - Mongoose.js findOne 返回查询元数据

redis - Redis 镜像目前是否可以在 Windows 上与 Docker 一起使用?

redis - Redis RDB 运行 bgsave 还是 save?