Reputation: 277
I would like to get my data out from the sqlite db.each function using the promise object and the async/await I tried to do it but I don't really understand how to do it and I would like some explanations
my code below :
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data.sqlite', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database');
});
function request (req) {
new Promise(function (resolve, reject) {
db.each(req, function (err, row) {
if (err)
reject(err);
else
data.push(row);
}, function (err, n) {
if (err) {
reject(err);
}
else
resolve(data);
});
});
}
data = await request("select * from user "); //I'm getting errors here
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection');
});
Upvotes: 4
Views: 1591
Reputation: 29282
await
can only be used inside an async
function. Create an async function, inside this function, await the promise
returned by request
function
async function makeRequest() {
data = await request("select * from user ");
}
and you need to return the promise from request
function so that it can be awaited
function request (req) {
return new Promise(function (resolve, reject) {
// code
});
}
Upvotes: 2