Reputation: 29
I was trying to figure out how to use sqlite with Node JS. I don't get how we can use the row when we ask the data base what we want. I looked everywhere on the web but nobody explain really how to use the row after the get is done.
I mean it returns the row but I can't use it.
const sqlite3 = require('sqlite3').verbose();
// open the database
let db = new sqlite3.Database('./db/chinook.db');
let sql = `SELECT PlaylistId id,
Name name
FROM playlists
WHERE PlaylistId = ?`;
let playlistId = 1;
// first row only
var test = db.get(sql, [playlistId], (err, row) => {
if (err) {
return console.error(err.message);
}
return row
? console.log(row.id, row.name)
: console.log(`No playlist found with the id ${playlistId}`);
});
//What I added to try to use the row after the get is done
console.log(test.id) // I get "undefined" here. How are we really suppose to do it?
// close the database connection
db.close();
This code comes from here
Upvotes: 0
Views: 62
Reputation: 141
try to use a Promise, for example:
const query = new Promise((resolve, reject) => {
var test = db.get(sql, [playlistId], (err, row) => {
if (err) {
reject(err);
}
resolve(row);
});
});
query
.then(data => console.log(data))
.catch(err => console.log(err));
Upvotes: 1