Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

428
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda