1

Please help trying to get this function to return value back to my main process. currently everything shows in the console however if I return the object its blank or undefined

const GetSelectDeviceFromDB = () => {
  db.all("SELECT * FROM device_list", function (err, rows) {
    rows.forEach(function (row) {
      console.log(row.device);
      return row.device;
    });
  });
};

module.exports = { GetSelectDeviceFromDB };

OUPUTS:
console.log =. { device1, device2 }
return = undefined and if I add the return to the beginning of the sql statement I get {}

Jerry Seigle
  • 417
  • 4
  • 12
  • `forEach()` doesn't return anything. Use `map()` to return a list of the result of each function. – Barmar Mar 01 '21 at 21:41
  • But `db.all()` is asynchronous. See https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Barmar Mar 01 '21 at 21:42
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phix Mar 01 '21 at 21:46

2 Answers2

2

Since all() method is asynchronous and it is using a callback, you can turn your method into a method like this:

const GetSelectDeviceFromDB = () => new Promise((resolve, reject) => {
  db.all('SELECT * FROM device_list', (err, rows) => {
    if (err) {
      reject(err);
    }
    const devices = rows.map((row) => row.device);
    resolve(devices);
  });
});

It will return a Promise, so you can call it like this:

GetSelectDeviceFromDB().then(devices => { ... })

Dan Cantir
  • 2,915
  • 14
  • 24
0

Returning from forEach isn't a good idea, returning from another object's method (db.all in you case) isn't either. You need to return exactly in the first scope of the lambda function, somewhere outside of db.all(...). But in this case it's an async method, so you should make your whole function async or a Promise