递归函数

时间:2018-03-14 09:31:06

标签: javascript node.js

我的响应是在数组上的递归函数推送值之前发送的。现在我正在实现Timeout功能。通过这个我得到了价值。但这不是一个正确的方法。如果任何人有更好的方法或想法,那么建议我。任何帮助都非常感谢。

var likepostidholder = [];

db.collection.find({}).sort({'createdate': -1}).limit(20).exec(function(error, data) {
 if(error){
  console.log(error)
} else {
  //create Recursive function which acts like loop
  var x = 0;
  var datalength = data.length;
  var recursiveFunction = function(length) {
    if (length > 0) {
      //I think There is some issue under this Db query.
 // Because if I console.log(x) then it returns the last number. If I write same console outside this Activity.find() query block then it returns all length one by one.
      Activity.find({'parentpost_id': data[x]._id}, {likes: {$elemMatch: {'userid': req.body.userid }}}, function(err, response){
   if (err) {
      console.log(err);
   } else {
     if(response.length !== 0) {
        if(response[0].likes.length == 1) {                                              
              likepostidholder.push(response[0]._id);
        }
     }

   }
});
     x++;
     return recursiveFunction(length - 1);
   } else {
     console.log('now my job is done');
     return length;
   }
  }
  recursiveFunction(datalength);
  setTimeout(function(e){
    res.send({"error":"false", "status":"200", 'likepostid': likepostidholder});
 },500);
}
});

1 个答案:

答案 0 :(得分:0)

在递归函数的中断条件下发送请求,如下所示:

您的递归函数执行异步无阻塞任务Activity.find Nodejs在处理下一个代码块之前不要等待此任务结束。

var likepostidholder = [];

db.collection.find({}).sort({'createdate': -1}).limit(20).exec(function(error, data) {
 if(error){
  console.log(error)
} else {
  //create Recursive function which acts like loop
  var x = 0;
  var datalength = data.length;
  var recursiveFunction = function(length) {
    if (length > 0) {
     //I think There is some issue under this Db query.
     // Because if I console.log(x) then it returns the last number. If I write same console outside this Activity.find() query block then it returns all length one by one.
      Activity.find({'parentpost_id': data[x]._id}, {likes: {$elemMatch: {'userid': req.body.userid }}}, function(err, response){
   if (err) {
      console.log(err);
   } else {
     if(response.length !== 0) {
        if(response[0].likes.length == 1) {                                              
              likepostidholder.push(response[0]._id);
        }
     }

   }
});
     x++;
     return recursiveFunction(length - 1);
   } else {
     console.log('now my job is done');
     res.send({"error":"false", "status":"200", 'likepostid': likepostidholder});
     return length;
   }
  }
  recursiveFunction(datalength);
}
});