0

I've got a function that returns a json with some data retrieved from a postgis database:

function ObtenerPuntosIniciales(TablaOrigen,callback)
    {  
        var conexion = "postgres://postgres:postgres2@"+ Server +"/" + BD;
        var sqlPunto='SELECT json FROM ' + TablaOrigen;
        pg.connect(conexion, function(err, client, done) {
            if(err) {
                return callback(new Error('ObtenerPuntosIniciales_error en la conexion:', err));
            }
            client.query(sqlPunto, function(err, Resultado) {
                  if(err) {
                    return callback(new Error('ObtenerPuntosIniciales_error al ejecutar la consulta:', err));
                  }
                  return callback(null,Resultado);
                  done();
            });                                                                               
        });
    }

After that i've got a code snippet that assigns the value returned by the function to a variable but this is always undefined although inside the function the value is being displayed:

var ObtainedData = ObtenerPuntosIniciales(TablaOrigenDeLosPuntos,function ( err,result ) {                                                                                                                                 
        if (err) {
                  console.log('Error:' + err);
                  return;
        }
        console.log('FunctionData:' +result.rows[0].json);
        return result;
});
console.log('ObtainedData:'+ ObtainedData); 

The console.log inside the function show the right value. The console.log outside the function,on the other hand, shows undefined.

Here is what the console is showing:

ObtainedData:undefined

GET /?ServidorOrigenDeLosPuntos=localgis-modelo&BDOrigenDeLosPuntos=geopista&Car
garCapas=true&NombreCapa1AMostrar=Circuitos&TablaCapa1=getxo_alum_circuitos_old&
TablaOrigenDeLosPuntos=getxo_alum_circuitos_old&NombreCampoClave1OrigenPto=id&Va
lorBuscadoCampoClave1OrigenPto=3 304 421ms

FunctionData:{"type":"LineString","coordinates":[[-3.009299817715526,43.3
46455178899078],[-3.009294275536192,43.346457831419585]]}

I guess the problem is in the function, that its not returning the value into the variable, or could be an async problem.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Egidi
  • 1,736
  • 8
  • 43
  • 69
  • Yes, it is a duplicate. @Aitor please take a look at the link posted above. – randunel Jan 15 '14 at 11:39
  • 1
    The link solves the problem of showing the data inside the function, which i already have that working (see i'm also using callback). What i need is to display it outside the function. – Egidi Jan 15 '14 at 11:59

1 Answers1

2

In NodeJS , If an operation in your code is async,Any code that uses that operation must be async too if you need to use the result of that latest async operation.

var ObtainedData = ObtenerPuntosIniciales(TablaOrigenDeLosPuntos,function ( err,result ) {                                                                                                                                 
        if (err) {
                  console.log('Error:' + err);
                  return;
        }
        console.log('FunctionData:' +result.rows[0].json);
        return result;
});


// the following will always be undefined
console.log('ObtainedData:'+ ObtainedData); 

So what can you do about it ? not much , except write another function to handle the next operation WITHIN the callback, or use a control flow library like async. In ES5 you cannot describe an async operation with a pseudo synchronous syntax. Some other languages allow that.

I would go with the async library ( pseudo code )

var async=require('async');

// given 2 functions connectDB and queryDB
async.series([connectDB,queryDB],function(err,result){
 //do some stuffs
});
mpm
  • 20,148
  • 7
  • 50
  • 55