I am trying to use async.waterfall to execute queries against a database sequentially so that I can rollback all of them if there is an error on one. Below is my code:
function _getDBConnection(callback) {
try {
dbService.getConnection(function(connection) {
callback(null, connection);
});
} catch (e) {
callback(e, null);
}
}
function _insertNewUser(newUser, connection, callback) {
if (connection) {
var query = 'somequery';
// Start a transaction
connection.beginTransaction(function(error) {
if (error) {
callback(error, connection, null);
}
// Fire the query
connection.query(query, function(error, result) {
if (error) {
callback(error, connection, null)
} else {
callback(connection, newUser, result.insertId);
}
});
});
} else {
callback('Error: no connection in ', null, null);
}
};
module.exports.doRegister = function(req, res) {
// Collect all the params coming from the UI.
var newUser = {'object with UI params'};
console.log("Trying to register the user...");
async.series([
_getDBConnection,
async.apply(_insertNewUser, newUser)
], function(err, success) {
if (err) {
console.log(err);
} else {
res.status(200).json({
success: true,
message: 'User registeration successfully.'
});
}
});
};
Problem: I am not receiving the connection object from _getDBConnection function into the second function (_insertNewUser) properly. It's coming as undefined, and as a result, I am getting the following error.
TypeError: connection.beginTransaction is not a function ~~~~ stack trace ~~~~ Error: Callback was already called ~~~~ stack trace ~~~~
I think I am getting the 'callback' function instead of the connection object in the _insertNewUser function, which is not expected. What am I doing wrong?
In case it matters, I have other functions/queries after the _insertNewUser that are getting called but, I have removed them from the code for brevity.