Home > Software engineering >  Requesting promise from sqlite database, await is not returning anything and async function won'
Requesting promise from sqlite database, await is not returning anything and async function won'

Time:02-28

I need to receive a promise from the sqlite database, but for some reason, await is not doing anything inside of async function, what to do or how do I get the data I need?

//SQLITE DB user check
function checkDBUser(userid) {
  return new Promise(() => {
  let author = userid
  let sql = `SELECT Author author
  FROM cooldowns
  WHERE author  = ?`;

  db.get(sql, [author], (err, row) => {

    if (err) {
      return console.error(err.message);
    }
    return row
    ? row.author && console.log('User found! '   row.author)
    : console.log('User not found!')
  }
  );
}); };

//Command for user check 
if(command === 'check') {
  async function checking() {
  const user = await checkDBUser(message.author.id);
  console.log('USER: ', user);
  console.log('random log') // even this .log is not returned by async function
  if (user == message.author.id) {
    console.log('User exists!')
    return;
  }
} checking();

Without await, checkDBUser(message.author.id); returns User: Promise { <pending> }, however with await, nothing is really logged at all, it's like literally not doing anything. I don't know where the problem is.

CodePudding user response:

You wrapped your db.get() in a new Promise(), but never called resolve or reject on that promise so that promise just never does anything (never resolves or rejects). Promises aren't magic. If you create one with new Promise(), you have to use the resolve and reject handler that are passed to the executor function and call them when the asynchronous operation is done.

Here's how that would look:

//SQLITE DB user check
function checkDBUser(userid) {
    return new Promise((resolve, reject) => {
        let sql = `SELECT Author author FROM cooldowns WHERE author  = ?`;

        db.get(sql, [userid], (err, row) => {
            if (err) {
                console.error(err.message);
                reject(err);
            } else {
                console.log(row);
                // resolve with row.author or null
                resolve(row ? row.author : null);
            }
        });
    });
}
  • Related