0

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.

legendofawesomeness
  • 2,901
  • 2
  • 19
  • 32
  • `dbService.getConnection( function(connection) `? I think that you don't need wrapper for `dbService.getConnection (err, connection)`. – Aikon Mogwai Nov 11 '17 at 01:50
  • Does not make a difference. Even after making that change, I get a [Function] for connection in _insertNewUser instead of getting an object and callback is undefined. – legendofawesomeness Nov 11 '17 at 03:29

1 Answers1

0

As i can see you are using async.series. Probably you should use async.waterfall to pass result of one function to another.

Nodejs async series - pass arguments to next callback

Pram
  • 2,383
  • 2
  • 19
  • 21