Skip to content Skip to sidebar Skip to footer

Array Of Queries For `for Await` Loop For Postgresql Transaction Helper

I made a transaction function that simplifies this action for me like this (it working): export async function transaction(queriesRaw) { let allResults = [] const client = awa

Solution 1:

Change this:

var queries = queriesRaw.map(q => {
  return client.query(q[0], q[1])
})

for await (const oneResult of queries) {
  allResults.push(oneResult)
}

To:

for(const q of rawQueries) {
   let result = await client.query(q[0], q[1]);
   allResults.push(result);
});

Solution 2:

If i got you correctly, Just use a for loop with proper await, instead of a callback style loop.

So you can wait with the function to return unil everything is chronologically executed, With some thinking, you can easily add aa revoke() function or something..


...
exportasyncfunctiontransaction(queriesRaw) {
  let allResults = []

  const client = await pool.connect()

  try {
    await client.query('BEGIN')

    for(var i = 0; i < queriesRaw.length;i++) {
        var res = await client.query(queriesRaw[i][0], queriesRaw[i][1])
        allResults.push(res)
    }

    await client.query('COMMIT')
  } catch (err) {
    await client.query('ROLLBACK') 

    // do you maybe wanna errors to results to?// allResults.push(err)
  } finally {
    client.release()
    return allResults
  }
}

Info,

Have a look at for example async module, or something similar. So you will not have to think about things like this.

Post a Comment for "Array Of Queries For `for Await` Loop For Postgresql Transaction Helper"