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

191
Visualizações
NodeJs: Promise always returns undefined

So I have the following promise that is supposed to go inside my sqlite database and tell me if there is a match. Even if the variables are correct it always returns undefined.

var checkLoanable = function(bookID){
    return new Promise((resolve, reject)=>{
        
        db.run('SELECT * FROM book WHERE id=?',[bookID],(err,row)=>{
            if (err) {
                console.log("error")
                reject();
                }
            if(row){
                
                if(row.loanable==0){
                    console.log("not loanable")
                    reject();
                        
                }
                console.log("success")
                resolve(row);
            }else{
                console.log("undefined")
                reject();
                    
            }
            console.log("End of promise")
        });
    
    })
}

This is the call of the function

await checkLoanable(bookID)
        .then(()=>{console.log("success")})
        .catch(()=>{
            res.status(422)
                .setHeader('content-type', 'application/json')
                .send({ message: "Failed to add loan: book is not loanable!"});
            
        });
        console.log("after promise");
        

The await is inside an async function and after tests I did it does wait for the promise to end and then continues the code. I can't figure out why its always undefined though. Thank you in advance for any help.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

run() is used for inserting and updating rows.

For getting a single row use db.get().

db.get('SELECT * FROM book WHERE id=?', [bookID] , (err,row) => { });

At least if you are using the npm/sqlite package.

about 4 years ago · Juan Pablo Isaza Relatório

0

Do not mix async/await and Promise chain use one of them.

Either with try...catch or Promise..then..catch

try {
  const book = await checkLoanable(bookID);
  res.json(book);
}catch ({message}) {
  res.status(422).send(message);
}

// or
checkLoanable(bookID)
  .then((book) => {res.json(book);})
  .catch(({message}) => {
    res.status(422).json({ 
      message: "Failed to add loan: book is not loanable!"
    });
  });

For the example if you use something like this

const myPromise = () => new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

(async () => {
  const result = await myPromise().then(data => {
    console.log({data});
  });
  console.log({result});
})();

Result would be

{data: 'Success!'}
{result: undefined}

Not both get values at the same time.

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