i have problem asynchrony of nodejs. hope can me.
exports.deviceinfo = function(req, res, next) { var nets = req.body.networks; db.collection("device", function(err, deviceconf) { var detected_beacons = []; if (!err) { (var = 0; < nets.length; i++) { deviceconf .find({ "data.number": nets[i] }) .toarray(function(errfind, saver) { if (!errfind && saver) { saver.foreach(function(disp) { var detected = {}; detected.address = disp.address; detected_beacons.push(detected); console.log(detected_beacons); }); } }); } console.log(detected_beacons); res.json(detected_beacons); } else { console.error(err); res.status(500); res.json({ message: "couldn't connect database" }); } }); };
if write logs, see problem. detected_beacons being returned before clause. want returned after for in order full of data. have read callbacks , promises don't know how use them in code.
try code. cannot loop concerning callback functions.
exports.deviceinfo= function(req,res,next){ var nets = req.body.networks; db.collection("device", function(err, deviceconf){ var detected_beacons = []; var netsize = nets.length; var beaconsloop = function(i) { deviceconf.find({"data.number" : nets[i]}).toarray(function(errfind, saver){ if (!errfind && saver){ var saversize = saver.length; saver.foreach(function(disp){ var detected = {}; detected.address = disp.address; detected_beacons.push(detected); saversize--; if (saversize == 0) { if (i != netsize - 1) { i++; beaconsloop(i); } else { res.json(detected_beacons); } } }); } }); }; if (!err){ if (netsize > 0) beaconsloop(0); } else { console.error(err); res.status(500); res.json({message:"couldn't connect database"}); } });
};
Comments
Post a Comment