ericdemo07
ericdemo07

Reputation: 481

How to retrieve Redis values into a array in NodeJs

I want to get all values from my redis and store it into a array in nodejs

Here is my present code,

redisClient.keys("Serial*", function (err, keys) {
    keys.forEach(function (key, i) {
        redisClient.hgetall(key, function (err, currencyData) {
            console.log(currencyData);
        })
    });
});

it allows me to output all values to console but I need to use these values

Upvotes: 1

Views: 1774

Answers (1)

Jyotman Singh
Jyotman Singh

Reputation: 11350

Assuming you need a the currencyData in an array -

function getAllCurrency(callback){
    redisClient.keys("Serial*", function (err, keys) {
        var allCurrencyData = [];
        var counter = keys.length;
        keys.forEach(function (key, i) {
            redisClient.hgetall(key, function (err, currencyData) {
                if(err)
                    return callback(err);
                console.log(currencyData);
                allCurrencyData.push(currencyData);
                counter--;
                if(counter == 0)
                   callback(null, allCurrencyData);
            })
        });
    });
}

Calling from another function -

getAllCurrency(function(err, allCurrency){
    // use allCurrency array here
});

This is not the best code. Also the order of elements in the array might not be the same as the keys array. For a better asynchronous control try using the async library or Promises.

Upvotes: 1

Related Questions