简体   繁体   English

如何从节点js中的for循环中获取值?

[英]How to get value from for loop in node js?

I want the last value from For loop to send the response (res.send). 我希望For循环中的最后一个值发送响应(res.send)。 If i give res.send in totalCost function im getting error response can't sent. 如果我在totalCost函数中给出res.send,则无法发送错误响应。 Pls help me to send the response. 请帮助我发送回复。

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
                }
            })
        }
    }
})

您的代码不清楚...但是我认为问题是您需要将“ res”作为参数传递给要使用res.send()的函数。

Thanks for your reply eventually i solved the code with async foreach.. 感谢您的答复,最终我用async 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()*/
            }
        } )
    }

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM