Search code examples
javascriptnode.jsnode-sqlite3

Passing results out of NodeJS database function to use outside of it


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?


Solution

  • 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.