2017-11-11 53 views
0

我正在尝试使用async.waterfall按顺序对数据库执行查询,以便在出现错误时可以回滚所有这些查询。下面是我的代码:Nodejs async.waterfall回调参数不匹配?

function _getDBConnection(callback) { 
 
\t try { 
 
\t \t dbService.getConnection(function(connection) { 
 
\t \t \t callback(null, connection); \t 
 
\t \t }); 
 
\t } catch (e) { 
 
\t \t callback(e, null); 
 
\t } 
 
} 
 

 
function _insertNewUser(newUser, connection, callback) { 
 
\t if (connection) { 
 
\t \t var query = 'somequery'; 
 

 
\t \t // Start a transaction 
 
\t \t connection.beginTransaction(function(error) { 
 
\t \t \t if (error) { 
 
\t \t \t \t callback(error, connection, null); 
 
\t \t \t } 
 

 
\t \t \t // Fire the query 
 
\t \t \t connection.query(query, function(error, result) { 
 
\t \t \t \t if (error) { 
 
\t \t \t \t \t callback(error, connection, null) 
 
\t \t \t \t } else { 
 
\t \t \t \t \t callback(connection, newUser, result.insertId); 
 
\t \t \t \t } 
 

 
\t \t \t }); 
 
\t \t }); 
 
\t } else { 
 
\t \t callback('Error: no connection in ', null, null); 
 
\t } 
 
}; 
 

 
module.exports.doRegister = function(req, res) { 
 

 
\t // Collect all the params coming from the UI. 
 
\t var newUser = {'object with UI params'}; 
 

 
\t console.log("Trying to register the user..."); 
 

 
\t async.series([ 
 
\t \t _getDBConnection, 
 
\t \t async.apply(_insertNewUser, newUser) 
 
\t ], function(err, success) { 
 
\t \t if (err) { 
 
\t \t \t console.log(err); 
 
\t \t } else { 
 
\t \t \t res.status(200).json({ 
 
\t \t \t \t success: true, 
 
\t \t \t \t message: 'User registeration successfully.' 
 
\t \t \t }); 
 
\t \t } 
 
\t }); 
 
};

问题:我没有收到来自_getDBConnection功能的连接对象进入第二功能(_insertNewUser)正确。这是未定义的,因此,我收到以下错误。

类型错误:connection.beginTransaction不是一个函数 ~~~~堆栈跟踪~~~~ 错误:回调已经叫 ~~~~堆栈跟踪~~~~

我想我获取'回调'函数而不是_insertNewUser函数中的连接对象,这是不期望的。我究竟做错了什么?

万一它很重要,我有_insertNewUser之后的其他函数/查询被调用,但为了简洁起见,我已将它们从代码中移除。

+0

'dbService.getConnection(功能(连接)'?我认为你不需要为'dbService.getConnection包装(ERR,连接)'。 –

+0

不有所作为,即使制作后这个改变,我在_insertNewUser中得到了一个[Function]来连接,而不是获得一个对象,并且回调函数是未定义的 – legendofawesomeness

回答