3

Every example I can find on sqlite3 and nodejs just writes the data to the console, which is useless - how do I await a data and return it from a calling method ? Lets say I have :

exports.selectData = function(tableName, parameters, successHandler) {
  var dbConn = new sqlite3.Database('./data/myAppsData.db');
  dbConn.all("SELECT " + parameters + " FROM " + tableName + "", function(err, rows) {
    // what to do here ? or somewhere else ?
  });
}

How do I get data (rows) to return from selectData ? Or alternatively, using successHandler callback ? (it is undefined where the comment is)

frno
  • 1,064
  • 11
  • 24
  • I would suggest returning `Promise` (`resolve(rows)` and `reject(err)`) but I don't know if that is what you wanted. Or something like this: https://stackoverflow.com/questions/21243327/how-to-return-results-of-nodes-sqlite3-in-a-function?rq=1 but with by replacing `callback` with `successHandler`. But before that, how do you call the `selectData()` function from outside? – ionizer Dec 08 '17 at 19:17
  • Could you post the code that is calling the selectData function? – jordanw Dec 12 '17 at 14:39

1 Answers1

-1
  dbConn.all("SELECT " + parameters + " FROM " + tableName + "", function(err, rows) {
    return rows // could replace with JSON.stringify(rows) If you want to pass JSON data
  });

Or as ionizer said you could return a promise. If you need to use async/await

exports.selectData = function(tableName, parameters, successHandler) {
  var dbConn = new sqlite3.Database('./data/myAppsData.db');
  return new Promise((resolve, reject) => {
   dbConn.all("SELECT " + parameters + " FROM " + tableName + "", 
    function(err, rows) {
     if(err) { 
       reject (err);
     } else {
       resolve(rows);
     }
   });
  });
}
jordanw
  • 1,495
  • 10
  • 13
  • I tried the first one before with no success, second one is also not working for me. – frno Dec 09 '17 at 19:53