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

126
Visualizações
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 Respostas
Responde à pergunta

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