Home > Enterprise >  returning a object gives undefined, using db.all() sqlite3 javascript
returning a object gives undefined, using db.all() sqlite3 javascript

Time:04-02

I don't understand why its console logging a undefined value instead of the object


function getusername( username ){ 
  let currentUsernameObj;
  sqlDB.all(sql, [username], (err, rows) => {
  if (err) {
    throw err;
  }
  if (!(rows.length === 0)&& username === rows[0].username) {
    console.log(username  " sqn "  rows[0].username );
    console.log(rows[0]);
    currentUsernameObj=rows[0];

  } else {
    console.log("user not found")
  }
  console.log(typeof(currentUsernameObj))
  return currentUsernameObj;
})};
var x=getusername("[email protected]");
console.log(x " yyyyyy");

this is my output output

I was expecting a object to be displayed and don't know what to do

CodePudding user response:

Your callback (see below) will be executed after the function has already returned and since you don't initialize currentUsernameObj to anything it is undefined.

// this callback is called after SQL returns the data
// as DB access is slow this will only be executed after your function has already returned
(err, rows) => {
  if (err) {
    throw err;
  }
  if (!(rows.length === 0)&& username === rows[0].username) {
    console.log(username  " sqn "  rows[0].username );
    console.log(rows[0]);
    currentUsernameObj=rows[0];

  } else {
    console.log("user not found")
  }
  console.log(typeof(currentUsernameObj))
  return currentUsernameObj;
}

You will have to await those results. Unfortunately SQLite does not have a Promise based API to make that easy so you will have to create the Promise yourself.

async function getusername(username) {
  // wrap the function in a Promise
  // resolve the promise on success
  // reject the promise on error
  return new Promise((resolve, reject) => {
    sqlDB.all(sql, [username], (err, rows) => {
      if (err) {
        // promise needs to be rejected as an error occurred
        reject(err)
      }
      if (!(rows.length === 0) && username === rows[0].username) {
        console.log(username   " sqn "   rows[0].username);
        console.log(rows[0]);
        currentUsernameObj = rows[0];
      } else {
        console.log("user not found");
      }
      console.log(typeof currentUsernameObj);
      resolve(currentUsernameObj);
    });
  });
}

// in order to be able to call an async method with await the call has to be in an async method itself
(async () => {
  // we can now use await to wait for the result
  var x = await getusername("[email protected]");
  console.log(x   " yyyyyy");
})();

For more information on async/ await and how to properly handle errors see the JavaScript docs, this tutorial or one of the countless YouTube videos that cover that in detail. Just search for async/ await or Promises.

  • Related