Controller层:
router.get('/toReg',function(req,res){ sexInfoService.getAllSexInfo(function(err,sexInfoArr){ console.log(sexInfoArr.length); res.render('loginAndReg/reg',{sexAll:sexInfoArr}); }); });
Service层 //获取所有性别的信息 sexInfoService.getAllSexInfo = function(callback){ var sexInfodb = mongodb.collection('sexInfo'); sexInfodb.find({},function(err,data){ if(err){ return callback(err); } var sexInfoArr = []; data.each(function(err,doc){ sexInfoArr.push(doc); }); return callback(err,sexInfoArr); }); }
module.exports = sexInfoService;
根据断点确实调用 sexInfoArr.push(doc); 了,但是 sexInfodb.find方法变成异步的了。 也就是说先经过Controller层toReg get方法,然后在进入Service层sexInfoService.getAllSexInfo的方法,但是经过sexInfodb.find的时候感觉直接略过,然后回到Controller层toReg sexInfoService.getAllSexInfo方法所以console.log(sexInfoArr.length) 时没有数据显示,这时候才开始触发Service层里的sexInfodb.find方法呢? 我这样写有什么问题吗?