NodeJS

时间:2015-08-17 18:33:15

标签: javascript node.js recursion express promise

我很难找到一种方法来进行递归,它等待一个任务/回调完成,然后在完成后执行另一个,例如我在我的& #39;加盟'方法:

exports.join = function(req, res){
  User.findById(req.user._id, function(err, user) {
     var dupe = []; //placeholder array
     var arr = user.forms_container.joinList;
     var title = user.forms_container.title;
     var myDate = Date();
     var newDoc = new Report();
     var tracker = 0;
     newDoc.author = req.user;
     var authorName = req.user.profile.firstName + " " + req.user.profile.lastName;
     console.log(authorName);
     newDoc.authors.set(0, authorName);
     newDoc.date = myDate;
     newDoc.owner = req.user;
     newDoc.title = title;
     //console.log(newDoc);
     newDoc.save();
     arr.forEach(function (rep) {
      console.log(rep);
                  Report.findById(rep).deepPopulate('subreport.subreport.subreport.subreport.subreport.subreport').execAsync()
                .then(function(doc) {
                    //console.log(doc);
                    dupe.push(doc);
                    treeCycle(doc, dupe);
                    console.log(dupe);

                    tracker = tracker + 1;

                    if (tracker == arr.length) {
                        //console.log(dupe); //returns [];
                        var counter = 0;
                        var masterbody ="";
                        for (var x = 0; x < dupe.length; x++) {
                            masterbody = masterbody + " " + dupe[x].body;
                            counter = counter + 1;
                        }
                        if (counter == dupe.length) {
                            newDoc.body = masterbody;
                            console.log(newDoc.body);
                            newDoc.save();
                            res.json(newDoc);
                        }
                    }

                }).catch(function(err) {
                    throw err;
                });
        });

    });
};

我使用了deepPopulate的承诺,但我不知道如何为我的treeCycle函数执行此操作,该函数只是遍历每个&#39; rep&#39; (在foreach中)并在其上进行深入填充,然后为我的阵列欺骗进行树循环。它正在做的是,如果我决定在[1,2,3]数组上运行连接,我希望它也按顺序连接,但是如果&#39; 1&#39;有一个子报告和&#39; 2&#39;和&#39; 3&#39;不要那么&#39; 2&#39;和&#39; 3&#39;将在1之前完成他们的树循环。然后&#39; doc&#39;包含&#39; 2&#39;&#39; 3&#39;&#39; 1&#39;的连接。所以我只想让treecycle等到#1;&#39; 1&#39;已经完成了。

TreeCycle:

function treeCycle(doc, arr) {
  if(doc.subreport.length != 0) {
    for (var x = 0; x < doc.subreport.length; x++){
      arr.push(doc.subreport[x]);
      //console.log(arr);
      if(doc.subreport[x].subreport.length != 0) {
        treeCycle(doc.subreport[x], arr);
      }
    }
  }
  else {
    return arr;
  }
};

0 个答案:

没有答案