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

125
Vistas
JS await not working as expected with pg query

I want to use the return of a query to a postgresSQL database. I don't want to just print it. I want to use it in another function. The problem is that the function here returns before it is finished with executing the code.

async function create_base_config(user_id, service_id, timer_seconds) {
    var ret
    var line
    await db_adm_conn.query(`
    INSERT INTO base_config (user_id, service_id, timer_seconds)
    VALUES ('` + user_id + "', '" + service_id + "', '" + timer_seconds + "') RETURNING id;", (err, result) => {
        if (err) {
            ret = false
            line = err
            console.log("line2 err : " + line)

        }
        else {
            ret = true
            line = result.rows
            console.log("line2 : " + line)
            // json_return = JSON.parse(result)
            // console.log(result.rows)

        }
    });
    console.log("line: " + line)
    return { ret_value: ret, line_value: line };
}

To test it i inserted debug prints. The output is:

server_1   | line: undefined
server_1   | line2 : [object Object]
 

so I am exectuting the code after the await before the await is finished. How can i fix that, so that he first executes all the code from the await and then the rest?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you should not use a callback function as the arrow function. You should use try catch like this:

async function create_base_config(user_id, service_id, timer_seconds) {
    var ret
    var line
    try {
        line = await db_adm_conn.query(`
    INSERT INTO base_config (user_id, service_id, timer_seconds)
    VALUES ('` + user_id + "', '" + service_id + "', '" + timer_seconds + "') RETURNING id;")
        ret = true
    }
    catch (err) {
        ret = false
        line = err
    }
    return { ret_value: ret, line_value: line };
}
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