javascriptnode.jsvariables

Variable undefined after assignment


Why is resultofgetCauses undefined? I'm not sure if the function is not returning currentCauses or if it not being assigned to resultofgetCauses . . . or if this has something to do with asynchronicity.

function getCauses(){

  var currentCauses;
  client = pg.connect(connectionString, function(err, client, done){

    if(err) console.log(err);

    client.query('SELECT * FROM causes', function(err, result){
      //console.log(result.rows);
      console.log('poo');
      currentCauses=result.rows;
      //console.log(currentCauses);
    });

  });

  return currentCauses;
};

var resultofgetCauses = getCauses();

Solution

  • Yes since it's running asynchronously, by the time result.rows is assigned to the currentCauses variable, the line return currentCauses has already been executed thus the value is undefined.

    You may want to do that as follow

    var resulttofgetCauses;
    function getCauses(){
        var currentCauses;
        client = pg.connect(connectionString, function(err, client, done){
            if(err) console.log(err);
            client.query('SELECT * FROM causes', function(err, result){
                //console.log(result.rows);
                console.log('poo');
                currentCauses=result.rows;
                //console.log(currentCauses);
                resulttofgetCauses = currentCauses;
            });
        });
    };
    getCauses();
    

    To be more specific with the answer, executing 'SELECT * FROM causes' sql does not give you the result right after its execution time. It takes at least 0.00something seconds to retrieve the data from database. So in the very short time between 'executing sql' and 'receiving requested data' JavaScript has already executed return currentCauses; while the correct data is still in the progress of retrieving. Because it's async and won't wait. There are good example code out there on the internet you may want to check out.

    Plus It's a good practice to define function as follow

    getCauses = function () { ... }