I am trying to figure out how to correctly set this block of code up so that the commit function will wait until all of the rows are inserted. Currently I am reading a csv and need to insert a new row per column into a table. I also need to add a row into a parent table for that. I need all of that to finish before I call commit. I have yet to master callbacks so please be gentle.
db.beginTransaction(function (err) {
if (err)
{
//could not begin a transaction for some reason.
logger.error("beginTransaction error: " +err);
}
//need to wrap this *************
db.query("INSERT INTO TABLE VALUES ('" + unique_id + "','real_time','" + msg + "',1,1,LOCALTIMESTAMP)", function(err){
if(err)
{
logger.error("error insert into parent table: "+err);
}
});
for(var i = 0; i < headers.length; i++)
{
//replaces single quote (') with two single quotes to escape it ('')
values[i] = values[i].replace("'","''");
db.query("INSERT INTO TABLE VALUES ('" + unique_id + "','" + headers[i] + "',0,'" + values[i] + "')", function(err){
if(err)
{
logger.error("error insert into child table: "+err);
}
});
}
//To here ************
db.commitTransaction(function (err) {
if (err)
{
//error during commit
logger.error("Commit error: "+err);
}
}); //end of commitTransaction
callback();
});//End of beginTransaction
There's three basic ways of tackling this synchronization problem which I'll demonstrate here using new style arrow functions. The traditional Node way is with callbacks:
This is what people refer to as "callback hell" because the nesting and error propagation code gets more and more ridiculous as your dependencies grow in complexity. I find this style unsustainable for any non-trivial application.
The next style is Promise-driven:
This tends to be a lot "flatter" and easier to follow, but it's still a lot of heavy syntax for what should be simple. The newer async/await style builds on promises by adding support for them to the JavaScript syntax:
This works inside any function tagged
async
like:Which can make your life a lot easier. You can also use conventional
try
/catch
notation for errors, they're propagated accordingly.