2017-11-11 16 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 }); 
 
};

問題:私は適切に第二の機能(_insertNewUser)に_getDBConnection関数から接続オブジェクトを受信して​​いません。定義されていないので、次のエラーが発生しています。

例外TypeError:connection.beginTransactionが機能 ~~~~スタックトレース~~~~ エラーではありません:コールバックは、すでに ~~~~スタックトレース~~~~

と呼ばれていた私は、私は考えます_insertNewUser関数内の接続オブジェクトの代わりに 'コールバック'関数を取得していますが、これは期待されていません。私は間違って何をしていますか?

重要な場合は、_insertNewUserの後に呼び出される他の関数/クエリがありますが、簡潔にするためにコードから削除しました。

+0

'dbService.getConnection(機能(接続)'?私はあなたが 'dbService.getConnection(ERR、接続)'のラッパーを必要としないと思います。 –

+0

は違いはありません。でも、作った後、その変更、私はオブジェクトを取得する代わりに_insertNewUserの接続のための[関数]を取得し、コールバックは未定義です – legendofawesomeness

答えて

0

async.seriesを使用しているのがわかります。おそらくasync.waterfallを使用して、ある関数の結果を別の関数に渡すべきでしょう。

Nodejs async series - pass arguments to next callback

+0

こんにちはPram、私は実際には滝で始まったが、結果はまったく同じだったので、私は無駄にシリーズを試していた。 :( – legendofawesomeness

関連する問題