javascript - 遍历 Redis 表,并在 Nodejs 和 Expressjs 中获取相同的键

标签 javascript node.js express redis

我使用相同的 key 将不同的数据保存在 Redis 的不同数据库中。例如,在这个脚本运行的任何时候,我在 Redis 的数据库 0...100 上都有键 test_1test_2。我想要做的是为每个数据库获取具有相同名称的 key ,并将数据保存到文件中。这是我尝试过的片段。

const redis = require('redis');
const client = redis.createClient();
const fs = require('fs');

for (let i = 1; i <= 100; i++) {
    client.select(i, function(err,res){
        client.mget(['test_1', 'test_2'], function(err,res){
            let results = JSON.parse(res);

            fs.appendFileSync('testfile.json', results);
        });
    });
}

我也试过将其包装在 async 函数中,并将 await client.mget 包装在异步函数中,但似乎没有任何效果。

最佳答案

您不能在 for 循环中进行这样的异步调用。你现在正在做的是告诉 Node 运行 100 个 select 语句,它会触发这些语句并且它们都会在不同的时间返回,然后它们将各自启动它们自己的 mget 并且最终你可能会让它们尝试附加到文件。这根本不是您想要的,即使它可以工作,您也不会得到任何合理的文件顺序。

有多种方法可以做到这一点,我想说最简单的可能是使用像 promise 库这样的东西,因为你想触发一堆异步请求,聚合结果,然后写入一个文件。

在这种情况下,我会执行如下操作。简短的免责声明,我没有运行代码,但我相信这应该通过一些调整大致工作。

const bluebird = require('bluebird');
const redis = require('redis');
const client = redis.createClient();

// Use bluebird to convert client.select and client.mget into
// promise returning functions rather than callback funcs.
// you could do this with the built in node utils, but we need
// some of bluebirds helper functions later on.
const rSelect = bluebird.promisify(client.select);
const rMget = bluebird.promisify(client.mget);

// Get 0..100 array, there are tons of ways to do this...
const dbIds = Array.from(Array(100).keys());

const operations = dbIds.map(id => {
    return rSelect(i)
        .then(res => {
            return rMget(['test_1', 'test_2']);
        });
});

// You now have an array of promises, one for each database id (0..100).
// We can now execute these promises using a bluebird helper.
// Here I'm using map, if you need them done in a specific order you could
// use mapSeries. You could also use reduce if you'd prefer writing it in
// a reducer style, but that doesn't seem to be what you want.
return bluebird.map(operations)
    .then(allResponses => {
        // "allResponses" now contains the response of every operation.
        // lets write those out to a file.
        var result = JSON.parse(allResponses);
        fs.appendFileSync('testfile.json', result);
    })

在上面的示例中,我使用了 Bluebirdjs 库,您可以随意使用任何您喜欢的库,但这应该可以完成工作。根据我的经验,使用 bluebird 进行迭代异步过程比使用回调要容易一些,因为它提供了一些不错的辅助函数。

关于javascript - 遍历 Redis 表,并在 Nodejs 和 Expressjs 中获取相同的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56873379/

相关文章:

javascript - jQuery - 不要在 'click' 上触发 'mousemove'

javascript - 使用来自 json 的 optgroup 创建 html 选择

c++ - NodeJS源代码找不到set_immediate_callback_function定义

node.js - 如何在CompoundJS中通过 "use"方法传递参数?

javascript - Observable 的转换

javascript - Express - 如何获取序列化表单

javascript - NodeJS x-ray web-scraper : how to follow links and get content from sub page

node.js - RestFul Api Node.js 和 Mongoose : handling errors

javascript - 无法读取未定义的从 Node 发送数组的属性 'length'到jade

javascript - Promise.race 在第一次履行后是否会拒绝其他 promise ?