0

Im working in a expressjs + sqlite small webapp for local use. But my problem is when I want to make a full select over a table. All my scripts are in JScript in 'use-strict' mode.

I want to make one SELECT statement and collect data in a json array named listadata. But the problem is that: until I don't declare this variable outside of the module.exports group -i.e. as a global variable- I cannot return any list of rows. If I delete that declaration, my function doesnt return anything.

This module must return a full list of rows. Please can anyone explain why I must declare this variable as global?. Or maybe is there a way to deal with this kind of statement in a more elegant way according to Javascript?

var listadata = [];

 module.exports = {
listas2 : function(){
    var db = sqlite.connect();
    db.all("SELECT * FROM TBWOHPARG", function(err,rows){
        listadata = [];
        rows.forEach(function(row){
            listadata.push({
                _id: row._id,
                descripcion: row.descripcion,
                fechacreacion: row.fechacreacion,
                fechamodificacion: row.fechamodificacion,
                referencia: row.referencia
            });
        });
    });
    return listadata;
}
nbro
  • 15,395
  • 32
  • 113
  • 196
MigRome
  • 1,095
  • 1
  • 12
  • 28

1 Answers1

0

db.all is asynchronous, so you will be returning listadata before it is populated

using callback, you can do something like

listas2 : function(callback){
    var db = sqlite.connect();
    db.all("SELECT * FROM TBWOHPARG", function(err,rows){
        listadata = [];
        rows.forEach(function(row){
            listadata.push({
                _id: row._id,
                descripcion: row.descripcion,
                fechacreacion: row.fechacreacion,
                fechamodificacion: row.fechamodificacion,
                referencia: row.referencia
            });
        });
    });
    callback(listadata);
}

but then when you call listas2 you can't do

something = listas2();
// do things with something

it would need to be

listas2(function(something) {
    // do things with something
}

Which is the same pattern of code as the duplicate question, just you are using a different asynchronous function, i.e. db.all instead of $.ajax

There's also a promise solution in the duplicate, which I wont reproduce

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87