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

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

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