I have confusing code that I'd like to modularize. I have a general ledger implemented in Mongodb. Transferring credits from john to adam appends the following document in the db.dummyTx:
{
"debitAccount": "john",
"creditAccount": "adam",
"amount": 10
}
I'd like to create a single function transfer(from, to, amount, callback()) where callback receives the transaction document/object.
I've created the following using the async module:
function transfer(from, to, amount, acallback) {
async.waterfall([
function(callback) {
userBalance(from);
userBalance(to);
callback(null);
},
function(callback) {
var transaction = new dummyTx();
transaction.creditAccount = from; // in the account of the sender
transaction.debitAccount = to; // with reference to the reciever
transaction.amount = amount; // of the given amount
transaction.save(function(err) {
callback(null, transaction);
});
},
function(transaction, callback) {
console.log("Credited User " + transaction.creditAccount +
" and debited User " + transaction.debitAccount + " by amount " +
transaction.amount + "credits");
callback(null, transaction);
},
function(transaction, callback) {
userBalance(transaction.creditAccount);
userBalance(transaction.debitAccount);
callback(null, transaction);
}
],
acallback(err, transaction)
);
}
My rationale was that if I pass function(err,transaction){if err console.log(err);} as acallback, it would run as the final callback in the end. However, it says err is undefined in acallback(err, transaction)
Bear with me, I just discovered async yesterday, so I'm a figurative five year old.
My second thought was to save the chain of functions into an Array named transfer and to call it as async(transfer,function(err,transaction){if err console.log(err)}; if I can't get this to work.
Edit: I'd also like the acallback parameter to be optional.
transaction.save? Also, why do you usewaterfallat all here when you have only a single async function?callback(err, transaction). And I just realized that I could do the same thing withasync.series. I've got another problem now though, theacallbackparameter now executes after the third function, with anullerror value, and then outputs the final function normally when I runtransfer(2, 1, 2, function(err, transaction) { if (err) { console.log(transaction); }});. Pastebin of output