0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Thai BNM
  • 1
  • 3

2 Answers2

0

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(); 
       });
    }
});
Hemanath
  • 1,075
  • 6
  • 15
0

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();
Thai BNM
  • 1
  • 3