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

3K
Vistas
How to do an If await by the async function response

I'm trying to create a function that checks if a table already exists in the database and if it doesn't, create one But the problem is the If doesn't await for checkTableExist()

const checkTableExist = async () => {
    console.log('starting check')
    db.query(`SELECT column_name
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE table_name = 'users'`, async (error, results) => {
        if (error) {
            console.log(error)
        }
        if (results !== null) {
            console.log('Not exist')
            return true
        }
        console.log('Exist')
        return false
    })
}


const createTable = async () => {
    await db.connect();
    if (await checkTableExist() !== true) {
        console.log('Creating Table')
        await db.query(`CREATE TABLE users (
             id SERIAL PRIMARY KEY,
             name varchar(100),
             email varchar(100),
             celular varchar(11),
             password varchar(255),
             validated boolean
         )`)
         db.end()
         return
    }
    db.end()
    console.log('Table already exist')
    return
}

createTable()

Console Log

starting check
Creating Table
Not exist
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In checkTableExist you are checking your DB Query results using a callback function. In there, when you return, you are not actually returning to the createTable function, you're getting back to checkTableExist.

If you use await, your returns should work correctly:

const checkTableExist = async () => {
  console.log('starting check')

  const results = await db.query(`SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'users'`);

  if (results !== null) {
    console.log('Not exist')
    return true
  }
  console.log('Exist')
  return false
})
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