skip to Main Content

I’m using redis and nodejs for the first time, without success. Trying to loop insert data but got an empty array.

const redis = require("redis");

const client = redis.createClient({
  retry_strategy: function(options) {
    if (options.error && options.error.code === "ECONNREFUSED") {
      // End reconnecting on a specific error and flush all commands with
      // a individual error
      return new Error("The server refused the connection");
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
      // End reconnecting after a specific timeout and flush all commands
      // with a individual error
      return new Error("Retry time exhausted");
    }
    if (options.attempt > 10) {
      // End reconnecting with built in error
      return undefined;
    }
    // reconnect after
    return Math.min(options.attempt * 100, 3000);
  },
});

var data_value = {
        id: '235235',
        totalrv: 'WAIT',
        product: 'productName2',
        url: 'url2',
        process: 'proc',
        task: 'msg'
    };

client.set("key0", JSON.stringify(data_value));
client.set("key1", JSON.stringify(data_value));
client.set("key2", JSON.stringify(data_value));
client.set("key3", JSON.stringify(data_value));
client.set("key4", JSON.stringify(data_value));

//client.get("key2", redis.print);

var logger_data = {
        logger: []
    };

client.keys('*', function (err, keys) {
    if (err) return console.log(err);

    for(var i = 0, len = keys.length; i < len; i++) {
        var values_v = client.get(keys[i].toString(), function(err, val) {
            // console.log(logger_data);
            // data is exist ...
            logger_data.logger.push(JSON.parse(val));
        });
    }
});

// empty data
console.log(logger_data);

I wrote 2 print data result, in the loop it’s working ok, but end of function, there are no data in array.

2

Answers


  1. Chosen as BEST ANSWER

    Ok, with help of CertainPerformance, it's now working in asynchronous. Thank you very much ...

    async function getMessage () {
        var logger_data = {
            logger: []
        };
    
        return new Promise(function(resolve, reject) {
            client.keys('*', function (err, keys) {
                if (err) return console.log(err);
    
                for(var i = 0, len = keys.length; i < len; i++) {
                    var values_v = client.get(keys[i].toString(), function(err, val) {
                        logger_data.logger.push(JSON.parse(val));
                        resolve(logger_data);
                    });
                }
            });
        });
    }
    
    async function main() {
        let message = await getMessage();
        console.log(message);
    }
    
    main();
    

  2. you can call a function inside the callback if you want to print the logger_data with values outside the asynchronous callback, like this

    function printLoggerData(){
     console.log(logger_data);
    }
    
    client.keys('*', function (err, keys) {
        if (err) return console.log(err);
    
        for(var i = 0, len = keys.length; i < len; i++) {
            var values_v = client.get(keys[i].toString(), function(err, val) {
                // console.log(logger_data);
                // data is exist ...
                logger_data.logger.push(JSON.parse(val));
                // calling the function here so that it contains the latest values
                printLoggerData(); 
           });
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search