javascript - Making async callback functions in nodejs -
i have confusing code i'd modularize. have general ledger implemented in mongodb. transferring credits john adam appends following document in db.dummytx:
{ "debitaccount": "john", "creditaccount": "adam", "amount": 10 } i'd create single function transfer(from, to, amount, callback()) callback receives transaction document/object.
i've created following using 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 account of sender transaction.debitaccount = to; // reference reciever transaction.amount = amount; // of given amount transaction.save(function(err) { callback(null, transaction); }); }, function(transaction, callback) { console.log("credited user " + transaction.creditaccount + " , debited user " + transaction.debitaccount + " amount " + transaction.amount + "credits"); callback(null, transaction); }, function(transaction, callback) { userbalance(transaction.creditaccount); userbalance(transaction.debitaccount); callback(null, transaction); } ], acallback(err, transaction) ); } my rationale if pass function(err,transaction){if err console.log(err);} acallback, run final callback in end. however, says err undefined in acallback(err, transaction)
bear me, discovered async yesterday, i'm figurative 5 year old.
my second thought save chain of functions array named transfer , call async(transfer,function(err,transaction){if err console.log(err)}; if can't work.
edit: i'd acallback parameter optional.
if have defined function acallback, should pass that, , not parameters. in other words, instead of this:
... } ], acallback(err, transaction) ); } ...use this:
... } ], acallback ); } to make acallback() optional, can number of things. couple things leap mind:
before calling,
async.waterfall(), check see ifacallback()defined. if not, set no-op function.before calling
async.waterfall(), check see ifacallback()defined. if not, invokeasync.waterfall()without it. if is, invoke it.
Comments
Post a Comment