我希望For循环中的最后一个值发送响应(res.send)。如果我在totalCost函数中给出res.send,我就会收到错误响应。请帮我发送回复。
viewCampaign.aggregate([
{$group:{_id:"$campaign",count:{$sum:1}}}
],function(err,arr){
if(err){
console.log(err)
} else {
console.log("arr",arr);
arr.forEach(function (val,index) {
var cid=arr[index]._id
var adCount=arr[index].count
totalCost(cid,adCount)
})
var totalAdCost=0
var totalEarn={}
function totalCost(cid,adCount){
console.log("adCount",adCount)
console.log(typeof(cid), "cid",cid)
campaignList.findOne({_id:cid},function(err,campaignDetails){
if(err){
console.log(err)
} else {
console.log("campaignDetails",campaignDetails.cost)
var costVal=totalAdCost+campaignDetails.cost*adCount
totalAdCost=costVal
}
})
}
}
})
答案 0 :(得分:0)
您的代码不清楚...但我认为问题是您需要将“res”作为参数传递给您要使用res.send()的函数;
答案 1 :(得分:0)
感谢您的回复,最终我用异步foreach解析了代码..
viewCampaign.aggregate([
{$group:{_id:"$campaign",count:{$sum:1}}}
],function(err,result){
if(err){
console.log(err)
}
else {
console.log(result)
var totalAdCost=0
async.forEach(result,function(item,callback){
var cid=item._id
var adCount=item.count
campaignList.findOne({_id:cid},function(err,campaignDetails){
if(err){
console.log(err)
}
else {
console.log("campaignDetails",campaignDetails.cost)
var costVal=totalAdCost+campaignDetails.cost*adCount
totalAdCost=costVal
callback()
console.log("totalAdCost Cost",totalAdCost)
}
})
},function(err){
if(err){
console.log(err)
callback(err)
}
else{
res.json({
success: true,
totalAdCost: totalAdCost
});
// res.send(totalAdCost)
console.log("Hello World",totalAdCost)
/*
res.send()
callback()*/
}
} )
}
})