function searchData(){
NodeInfo.find({}, function(err, res){
if(err) {
console.log("Error:" + err);
}
console.log(JSON.stringify(res,null,2)); //1处
return res;
})
}
let a = searchData();
console.log(a); //2处
为何打印1处能显示出完整的数据,打印2处却提示undefined,要如何才能将查找到的数据保存到数组中?
因为查询需要耗时,所以
find
是异步方法,第二个会console.log先执行,执行的时候查询还没有完成,而且searchData
本身没有返回值,所以a为undefinded
,查询完成后才会执行find
的callback,才会执行第一个console.log,所以第一个console.log可以打印出结果mongoose应该是支持promise的,所以可以这么写: