Reputation: 623
I am using an AWS Node.js lambda function and I am attempting to insert into multiple tables in my MySQL database. I am using the mysql node package. I have two tables (header and detail) in the database. I have an array of JSON objects that includes the header info with an array of the detail info inside the object. It looks like this:
{
id:1,
name: "bob",
detail: [salary: 50000, age: 35]
}, {
id:1,
name: "jane",
detail: [salary: 60000, age: 28]
}
I need to loop through each object in this array and populate:
I tried using the standard "mysql" library for Node.js, but due to the nature of the connectoin.query(sql, fn), the second parameter is a callback, and I'm not sure how I would pull this off. I'm not sure how I could loop through the headers and details within the headers using the standard mysql library since the .query function requires a callback and not a Promise
Thanks
Upvotes: 0
Views: 2577
Reputation: 24555
You could use the promisify
utility from the nodejs utils package to wrap the mysql (or specific functions in the module) in a Promise, allowing you to use async/await. Something like this:
const mysql = require('mysql')
const util = require('util')
const pool = mysql.createPool({ ... })
...
pool.query = util.promisify(pool.query)
...
try {
var result = await pool.query('SELECT * FROM users')
} catch(err) {
throw new Error(err)
}
Upvotes: 1