1const mysql = require('mysql2/promise')
2
3/** See documentation from original answer */
4async function transaction(queries, queryValues) {
5 if (queries.length !== queryValues.length) {
6 return Promise.reject(
7 'Number of provided queries did not match the number of provided query values arrays'
8 )
9 }
10 const connection = await mysql.createConnection(databaseConfigs)
11 try {
12 await connection.beginTransaction()
13 const queryPromises = []
14
15 queries.forEach((query, index) => {
16 queryPromises.push(connection.query(query, queryValues[index]))
17 })
18 const results = await Promise.all(queryPromises)
19 await connection.commit()
20 await connection.end()
21 return results
22 } catch (err) {
23 await connection.rollback()
24 await connection.end()
25 return Promise.reject(err)
26 }
27}
28