node.js - How to make node js api synchronous to fire mongodb's multiple queries? -
i have api in node.js find id of category name , when result comes send id in function , calls of parent categories id.if there no parent category in array should added , if there parent category should added in array.my problem response send blank array because of asynchronous call.how make synchronous through async-waterfall ?please me .thank in advance
router.post('/api/getproductofcategory', function(req, res) { var name = req.body.category; var cidarray = []; category.getcategoryidbyname(name, function(err, categoryid) { if (err) { throw err; } if (categoryid.length) { console.log(categoryid); category.getcategorywithsameparentfun(categoryid[0]._id, function( err, categorywithsameparent ) { if (err) { throw err; } else { console.log(categorywithsameparent); if (categorywithsameparent.length == 0) { cidarray.push(categoryid[0]._id); } else { cidarray.push(categorywithsameparent._id); } product.getproductbycategoryid(cidarray[0], function(err, products){ if(err){ console.log('error', err); } else{ console.log(products); } }) } }); } }); res.end('result', cidarray); });
i changed variable names bit , made comments. don't know why want send cidarray api response anyway how control flow async/each.
const each = require('async/each'); router.post('/api/getproductofcategory', function(req, res) { var name = req.body.category; var cidarray = []; category.getcategoryidbyname(name, function(err, categoryids) { if (err) { throw err; } each( categoryids, function(categoryid, callback) { category.getcategorywithsameparentfun(categoryid._id, function( err, categorywithsameparent ) { if (err) { throw err; } else { if (categorywithsameparent.length == 0) { cidarray.push(categoryid[0]._id); } else { cidarray.push(categorywithsameparent._id); } callback(); } }); }, function(err) { // here cid array filled desired values. each( cidarray, function(cid, callback) { product.getproductbycategoryid(cid, function(err, products) { if (err) { console.log('error', err); } else { // don't know you're trying products here. // whatever should call callback() after job each cid. console.log(products); } }); }, function(err) { // final step. end response here. res.end('result', cidarray); } ); } ); }); });
Comments
Post a Comment