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

151
Visualizações
Combing async function and sql query

I'm new to async functions and I'm struggling getting it do work with db queries... Here's what I have:

fetch: async (id) => {
  if (id!=='something') {
    return await db.getConnection().query("SELECT user FROM `table` WHERE id='" + id + "'", function (err, result) {
      if (err) { throw err }
      else {
        console.log(result[0].user);
        return result[0].user;
      }
    });
  }
  throw new Error('Failed fetching installation');
}

This results in getting an error: Cannot read property 'user' of undefined , but after this error, the console.log comes in indicating result[0] is actually defined.

So my guess is that it's not waiting for the result or something like that (even though it's not hitting the throw new Error). Anyway, I'm sure this is just me not getting this right... as said, I'm only just getting started with these kinds of async behaviors.

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

0

As mentioned above you are mixing promises and callbacks. I am unsure if my example below is possible with your database library, but I think if it is, its a much cleaner approach.

const fetch = async (id) => {
  if (id !== 'something') {
    try {
      const query = await db
        .getConnection()
        .query("SELECT user FROM `table` WHERE id='" + id + "'")
      return query[0].user
    } catch (error) {
      console.log(error)
      throw new Error(`Execution of query failed with error: ${error}`)
    }
  }
  throw new Error('Failed fetching installation')
}
const user = fetch('your-id') // (prefix fetch with await if not at top level)
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