Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!