我正在学习Node.js。当前,我面临如何在当前函数定义中访问回调函数返回的值的问题?
var list = async(req,res,next) =>
{
let dataQuery = {};
let responseArray = [];
let dataArray = [];
let global = {};
let records;
if(req.query.type_name != '') {
dataQuery = {
type_name: req.query.type_name,
status:1
}
} else {
dataQuery = {
status:1
}
}
Banner.find({},
(err, banners,callback) => {
if(banners.length > 0) {
responseArray.length = 0;
for(let i=0; i<banners.length; i++) {
getBannerProducts(banner_id, function(err, result) {
dataArray[i] = {
_id:banners[i]._id,
name:banners[i].name,
products:records
};
});
responseArray.push(dataArray[i]);
}
res.status(200).json(responseArray);
});
}
var getBannerProducts = function(banner_id, callback) {
BannerProductModel.aggregate([
{
$lookup:{
from: "products",
localField: "product_id",
foreignField: "_id",
as: "product"
}
},
{
'$match': {
banner_id: mongoose.Types.ObjectId(banner_id)
}
} ,
{
"$unwind": {
path: "$product",
preserveNullAndEmptyArrays: true
}
} ,
{
'$project':{
_id : 1,
banner_id : 1,
product_id : 1,
product: {
name : "$product.name",
_id : "$product._id",
},
}
}
], function(err, records) {
callback(err, records);
});
}
结果应该是这样
结果: [ { _id:“ 787454545dsds”, 名称:“横幅一”, 产品:[ { _id:“ 745454554sds”, 名称:“产品一” }, { _id:“ 745454554sds33”, 名称:“产品二” } ] }, { _id:“ 787454545dsds23”, 名称:“横幅二”, 产品:[] } ]