1

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

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

allCurrencyData cannot be modified from inside another function. here hgetall is a function allCurrencyData will be a seperate variable when used inside hgetall

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.