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

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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