Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

429
Vistas
returning a object gives undefined, using db.all() sqlite3 javascript

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("user2@s.com");
console.log(x+" yyyyyy");

this is my output output

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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("user2@s.com");
  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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda