从Node中的单个函数返回多个响应(sails js)

时间:2016-05-25 08:44:50

标签: javascript angularjs node.js

我正在使用Angular js和Sails开发Web应用程序。现在我遇到了一个问题。在我的应用程序中有一个菜单,它显示了来自database.Plz的不同计数值,请看我的背面

getAllCountMyProfile: function(req,res){
UsertokenService.checkToken(req.get('user-token'), function (err, tokenCheck) {
var userId = tokenCheck.tokenDetails.userId;
 var query = "select (select count(*) FROM review WHERE userId="+ userId +" AND approvalStatus = 'approved') AS reviewReceived ,"+
      " (select count(*) FROM review WHERE reviewerId="+ userId +" ) AS reviewPenned, "+
      "(select count(*) FROM photos WHERE userId="+ userId +" AND accessType='private' AND status='active') AS privatePhotoCount, "+
      "(select count(*) FROM photos WHERE userId="+ userId +" AND accessType='public' AND status='active') AS publicPhotoCount";
 Review.query(query, function (err, photoReviewCount) {
        if(err){
            console.log("Error"+ err);
        }
        else{

            return res.json(200, {status:4, message:'success',data1:photoReviewCount});
        }
    });
UserService.checkVideoLimit(userId, function (err, videoCount)
       {

        var noVideos=videoCount.data;
        console.log("Video count "+noVideos);
        return res.json(200, {status: 1, data2: videoCount});

    });
var query="SELECT sum(rating) AS totalRating,COUNT(*) AS totalCount FROM review where userId=" +userId+ "";
       Review.query(query, function (err, avgRating) {
        if(err){
            console.log("Error"+ err);
        }
        else{
            var rating=JSON.stringify(result);
            var totalRating=result[0].totalRating;
            var count=result[0].totalCount;
            var avgRatingValue=(totalRating/count).toFixed(2);
            console.log(totalRating,count);
            console.log("avgRating"+rating);
            return res.json(200, {status:4, message:'success',data3:avgRating});
        }
    });
   });`
}

如果我执行每个返回响应,我得到了结果。如果我执行上面的查询,我在控制台上收到错误消息 "发送后无法设置标头。" 我需要结果data1,data2,data3。获得这个的解决方案是什么?

1 个答案:

答案 0 :(得分:0)

您无法多次设置响应。您可以使用res.write并编辑查询响应,然后使用res.end()发送它,或者您可以更改代码以仅发送一次响应。像这样:

res.status(200).json({
     "data":{
          "data1":photoReviewCount,
          "data2":videoCount,
           "data3":avgRating
            }
})