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

99
Visualizações
How to make sure one query executes after the other in async javascript function

As you can see below, I've set up a Postgres database and create a User Profile for each user. Then, I get the user ID and set the result of that query to 'res'. From there, I pull out the User ID value and run another query using the it. The only problem is this: I think sometimes these statements are executing out of order, because the user gets an empty string sent back to them.

app.post('/createUser', async function (request, response) {
  const client = await pool.connect();
  let phoneNumber = request.body.phoneNumber;
  try {
    await client.query('BEGIN')
    await client.query(`INSERT INTO table (p_num) VALUES($1) ON CONFLICT DO NOTHING RETURNING *`, [phone]); //create a row in 'table' with user id and some values related to the user
    let res = await client.query('SELECT * FROM table WHERE p_num = ($1)', [phone]) //fetches user id from the recently generated row in 'table'
    var id = 0;
    // res.rows should only return one row because the ID is a unique generated identifier, it's hacky but I wasn't sure how to do this better
    for (row of res.rows) {
      id = row.id;
    } 
    await client.query('INSERT INTO table2 (uid) VALUES($1) ON CONFLICT DO NOTHING', [id]) //use the user id to run a query on another table
    await client.query('COMMIT')
  } catch (err) {
    await client.query('ROLLBACK')
    console.log(err)
  } finally {
    client.release()
    response.send(String(id))
  }
});

\d table returns:

Column        |  Type   | Collation | Nullable |                Default                 
--------------+---------+-----------+----------+----------------------------------------
 id           | integer |           | not null | nextval('userstable_id_seq'::regclass)
 phonenumber  | text    |           |          | 
 total_logins | integer |           | not null | 0
Indexes:
    "userstable_pkey" PRIMARY KEY, btree (id)
    "unique_p_num" UNIQUE CONSTRAINT, btree (p_num)
about 4 years ago · Juan Pablo Isaza
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