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

98
Visualizações
Having trouble returning a promise and then consuming it after a database call

Im learning Javascript and im up to a section on Promises. So decided to try and convert some of my earlier projects to use Promises. But I cant get my head around it. Iv read a lot of guides and browsed through this site but I still cant understand why this isnt working.

This the function im working with, trying to do a database call that returns a promise, that can then be logged or whatever.

const getID = function (product) {
  let query = `select typeID from invTypes where UPPER(typeName) =UPPER('${product}')`;
  return new Promise((resolve, reject) => {
    resolve(
      DB.get(query, function (err, result) {
        if (err) {
          Bot.say(`Error looking up ${product}`);
        } else {
          console.log(result.typeID); //587
          return result.typeID;
        }
      })
    );
  });
};

getID(product).then((data) => console.log(data)); //Database {}

The console outputs

Database {}
587

so the .then(data => console.log(data)) //Database {} Is still happening before the promise is returned,

as you can see the other log from earlier up inside the function is actually logging after it.

Can someone help me with this iv been at this one function for hours now haha. I think I have some kind of fundamental misunderstanding that Im not picking up on from my bootcamp videos or anything im reading.

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

0

In promise code, you use resolve() in the asynchronous function's callback function to return values.

const getID = function(product) {
  let query = `select typeID from invTypes where UPPER(typeName) =UPPER('${product}')`;
  return new Promise((resolve, reject) => {
    DB.get(query, function(err, result) {
      if (err) {
        Bot.say(`Error looking up ${product}`);
        reject(`Error looking up ${product}`);
      } else {
        console.log(result.typeID); //587
        resolve(result.typeID);
      }
    })
  });
};

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