2

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();
Kinnard Hockenhull
  • 2,790
  • 5
  • 27
  • 34
  • 3
    Asynchronous code? See here http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs Oct 28 '13 at 23:08
  • I don't think it's the asynchronicity that's the problem though – Kinnard Hockenhull Oct 28 '13 at 23:14
  • 1
    It is, `currentCauses` is `undefined` as `resultofgetCauses` gets assigned **before** `pg.connect` has time to finish. That question has an in-depth solution to your problem. – elclanrs Oct 28 '13 at 23:16
  • 1
    There are actually 2(nested) async calls here. `pg.connect` and `client.query` – dwerner Oct 28 '13 at 23:18

2 Answers2

3

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 () { ... }
Eugene Yu
  • 3,708
  • 4
  • 21
  • 27
0

Because currentCauses is initialized in an async invoked function (the function passed as param to pg.connect) after you have already returned from getCauses function. By the time you return the value of currentCauses is undefined.

Lachezar
  • 6,523
  • 3
  • 33
  • 34