2

I'm currently trying to retrieve data from a sqlite query in node.js, the sql function is on a diferent file so i'm exporting it as a module and then call the function from the index.js. But when i try to retrieve the data the function returns a null value.

Here is my code

Index.js

var express = require("express");
var body_parser = require("body-parser");
var app = express();
var db = require('./dbhandler.js');

app.set("view engine", "jade");

app.get("/data",function(req,res){
   let data = db.select();
   res.send(data);
});

app.get("/",function(req,res){
   res.render("index");
});

app.listen(8888);

dbhandler.js

var sqlite3 = require("sqlite3");

const file = "hr";

exports.select = function (){

var lista = [];

var db = new sqlite3.Database(file);

db.all("SELECT * FROM usuarios", function(err,rows){

    let contador = 0;

    rows.forEach(function (row) {
            lista[contador] = row.nombre + ";" + row.cedula + ";" + row.edad + ";" + row.pais;
    });
});

db.close();

return lista;
}

1 Answer 1

11

Node is asynchronous!!!. lista is returned from the module before the db.all function completes.

You either need to pass a callback into the select function or return a promise. The callback approach would look something like this:

 exports.select = function (cb){
    var lista = [];
    var db = new sqlite3.Database(file);           
    db.all("SELECT * FROM usuarios", function(err,rows){
         if(err) return cb(err);
         let contador = 0; 
         rows.forEach(function (row) { 
            lista[contador] = row.nombre + ";" + row.cedula + ";" + row.edad + ";"
    + row.pais; }); 
        db.close();
        return cb(null, lists);
}); 
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked. I started learning node about 3 days ago and never tried to learn about callbacks until now so i had no idea how to fix it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.