I want to make sure the database opens properly, then execute the get statement, then output it. But I am the following in the console where it's getting executed simultaneously. Thanks in advance!
Console log:
here1
here2
usergp is undefined
usergp in get is 10931
Desired output:
here1
usergp in get is 10931
here2
usergp is 10931
Code:
let selectGP = 'select gp from Money where userID = ? and guildID = ?';
let userGP;
let db;
const openDB = new Promise(resolve => {
db = new sqlite3.Database('./Toothless.db', (err) => {
if (err) {
console.error(err.message);
}
});
resolve();
});
x = openDB.then(() => {
console.log('here1');
db.get(selectGP, [interactionUserID, interactionGuildID], (err, row) => {
if (err) {
console.log('in test > select GP');
} else {
userGP = row.gp;
console.log('usergp in get is ' + userGP);
return userGP;
}
});
}).then((data) => {
console.log('here2');
console.log('usergp is '+ data);
interaction.reply({
content: 'you have ' + data
, ephemeral: true
});
db.close();
}).catch(() => {
console.log('in catch');
});
you're not returning any value from the first step of the promise chain, thus breaking it, so data in the next step will always remain empty.
does db.get return a promise? if so, you can return that (or declare the first step as an async function, and return the awaited value, i.e. return await db.get(...). as comments mentioned - async/await is not the point here - it's just another way to express the nested asynchronous flow you're after)
in any case, you should also omit the db.get callback, and move that logic to the then callback.
it would be a good idea to throw any error from the database (after logging them or whatever), so it is caught by the later catch() step
if your aim is to change the order of execution, and db.get does not provide promises to work with, you can either wrap it with a promise yourself (tedious), or use a helper library for such flows, like async, that also has utilities for such wrappings (easy).