0

I have the following code I am using with a SQLite3 npm module.

db.all("SELECT * FROM posts WHERE id = '3', function(err, rows) {
   return rows
})

I would like to access the data from rows outside of this code, for example...

db.all("SELECT * FROM posts WHERE id = '3', function(err, rows) {
   return rows
}) 

// >>> *** I want to call the results for rows here ***

Could someone explain with a quick example how this is done?

Gogol
  • 3,033
  • 4
  • 28
  • 57

2 Answers2

0

You can make a use of promises, for example:

new Promise(function (resolve, reject) {
  db.all("SELECT * FROM posts WHERE id = '3', function(err, rows) {
    // Check if there's an error, if it exists the promise will end up.
    if (err) {
      reject(err)
      return
    }

    resolve(rows)
  })
}).then(function (rows) {
  // You can make use of your code here
}).catch(function (err) {
  console.log(err)
})

Promises act asynchronously so it will be resolved once the data is readed from your db.

You go here to learn a little bit more. The documentation is awesome.

Arnold Gandarillas
  • 3,896
  • 1
  • 30
  • 36
0

You can't access rows from outside the callback, because is asynchronous, the callback is telling you when you can actually use it.

However, you could use async / await if you are not keen on nested callbacks:

const { promisify } = require('util');

const dbAllAsync = promisify(db.all);

(async function() {
    const rows = await dbAllAsync("SELECT * FROM posts WHERE id = '3'");
    console.log(rows); // you can use rows here
})();

Caveat:

Check if your version of node supports promisify. If it doesn't use a library such as bluebird. Same applies for async / await, in this case you could use a transpiler such as babel, or just upgrade node :)

Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44