簡體   English   中英

在遞歸函數之前重新發送觸發器

[英]Res.send trigger before recursive function

我的響應是在數組的遞歸函數推入值之前發送的。 目前,我正在實現超時功能。 通過這種方式,我獲得了價值。 但這不是正確的方法。 如果有人有更好的方法或想法,那么建議我。 任何幫助都非常感謝。

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

在遞歸函數的中斷條件下發送請求,如下所示:

您的遞歸函數執行一個異步無阻塞任務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);
}
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM