ad1tya2
ad1tya2

Reputation: 35

How to assign a variable to the output of a sqlite query in node js

What I am doing right now is:

db.get(`SELECT * FROM '${message.guild.id}'`,(err, row) => {
    console.log(row.channel);
});

What I basically want to do is, something like this:

let xyz = db.get(`SELECT * FROM '${message.guild.id}'`,(err, row) => {
    return row.channel;
});
console.log(xyz);

Upvotes: 3

Views: 1766

Answers (1)

Dominik
Dominik

Reputation: 6313

Your db function uses a callback. A callback is run async to your code so JS will not wait for it and will continue to execute the code below. That means you won't be able to assign a variable like you suggested.

What you could do is create an async function you can await in your code:

async function getChannelFromID(db, id) {
    return new Promise((resolve, reject) => {
        db.get(`SELECT * FROM '${id}'`,(err, row) => {
            if (err) reject(err); // I assume this is how an error is thrown with your db callback
            resolve(row.channel);
        });
    });
}

// Now you can use the function like this
// (make sure you mark the function you call this in as async)
const xyz = await getChannelFromID(db, message.guild.id);

Upvotes: 6

Related Questions