So, I am trying to make a thing with discord js and sqlite3 but I've been stuck on this one issue for the past few hours and I still do not understand how I would resolve it.
client.countDB = function(discordID) {
const arr = [];
db.each(`SELECT count(DiscordID) FROM verification WHERE DiscordID = ${discordID}`, function(err, row){
if(err){console.log(err); return 0;}
arr.push(Object.values(row))
return arr;
})
return arr[0];
};
So I am trying to get data that is only available in db.each
but I do not know how I would pass it out so I can return the expected value. I've already tried using global variables, putting it in a larger scope, and I still cannot figure out how to do it.
Sorry if I am confusing I'm not used to asking questions all the time.
Edit: Should have said I'm using the npm sqlite3 module. https://www.npmjs.com/package/sqlite3
wrap your code in a function to make it synchronous, reference
var deasync = require('deasync');
function syncFunc()
{
let arr;
client.countDB = function(discordID) {
db.each(`SELECT count(DiscordID) FROM verification WHERE DiscordID = ${discordID}`, function(err, row){
if(err){console.log(err); arr = null;return;}
const tmp = []
tmp.push(Object.values(row))
arr = tmp;
})
};
while((arr === undefined))
{
deasync.runLoopOnce();
}
return arr[0];
}
If you have data in query easiest way to do is using promise.
client.countDB = function(discordID) {
return new Promise((resolve, reject) => {
db.each(`SELECT count(DiscordID) FROM verification WHERE DiscordID = ${discordID}`, function(err, row){
//if you want to throw as an error, reject promise with the incoming error as "reject(err)"
if(err){console.log(err); return resolve(0);}
arr.push(Object.values(row))
return resolve(arr[0]);
})
})};
// You can use this as
client.countDB('someId')
.then(data => console.log(data))
.catch(err => console.log(err));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.