javascript - Breaking down Callback Hell how do I pass a value? -
using monoskin in express route i'm doing following:
router.get(/getbuyerinfo, function(req, res) { var data = "data"; db.collection('buyerrec').find().toarray(function(err, result) { if (err) throw err; console.log(result); db.collection('buyerhistory').find().toarray(function(err, result) { if (err) throw err; console.log(result); console.log(data); }); }); });
it's deeper. in attempt clean deep callbacks, in straight forward , quickest manner, if not modern way, created:
router.get(/getbuyerinfo, getbuyerrec); function getbuyerrec(req, res) { var data = "data"; db.collection('buyerrec').find().toarray(getbuyerhistory); } function getbuyerhistory(err, result) { if (err) throw err; console.log(result); db.collection('buyerhistory').find().toarray(function(err, result) { if (err) throw err; console.log(result); console.log(data); }); }
my problem 'data' no longer in scope. 'data' value came express router.get(). how pass 'data' getbuyerhistory function can use it?
assuming have along lines of:
(function () { var data = "data"; db.collection('buyerrec').find().toarray(getbuyerhistory); }()); function getbuyerhistory(err, result) { if (err) throw err; console.log(result); db.collection('buyerhistory').find().toarray(function(err, result) { if (err) throw err; console.log(result); console.log(data); }); });
you can create function returns function, , pass data
in parameter:
function factory(data) { return function getbuyerhistory(err, result) { ... }; }
which can call create function pass toarray
:
(function () { var data = "data"; db.collection('buyerrec').find().toarray(factory(data)); }());
alternatively, if you're not otherwise using this
within getbuyerhistory
, bind data
context , pass bound function toarray
:
(function () { var data = "data"; db.collection('buyerrec').find().toarray(getbuyerhistory.bind(data)); }());
alternatively, @bergi correctly pointed out, can add parameter getbuyerhistory
, use bind
without context:
(function () { var data = "data"; db.collection('buyerrec').find().toarray(getbuyerhistory.bind(null, data)); }()); function getbuyerhistory(data, err, result) { ... }
Comments
Post a Comment