2017-02-27 79 views
0

我想從For循環的最後一個值發送響應(res.send)。如果我給res.send totalCost函數我得到的錯誤響應不能發送。請幫我發送回覆。如何從節點js中的for循環獲取值?

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

http://stackoverflow.com/questions/29738535/catch-foreach-last-iteration – dmoo

回答

0

您的代碼是不明確......但我認爲問題是,你需要通過「資源」作爲參數,從那裏你想使用res.send()函數;

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()*/ 
      } 
     }) 
    } 

})