递归回调

时间:2013-04-05 05:23:16

标签: javascript node.js

需要一点帮助才能让这个面包屑构建器正常工作 - 这是对父类别的递归获取,应该返回一系列条目。不太正常,我的大脑被炒了....目前只返回最后一个条目。

var walk = function(c, done) {
  var results = [];
  Category.findById(c).exec(function(err, cat) {
    if(cat) {
      results.push({ title: cat.title, id: cat.id});
      if(cat.parent) {
        walk(cat.parent, function(err, res) {
          results = results.concat(res);
        });
      }
      return done(null, results);
    }
    done(results);
  });
};

walk(product.categories[0].id, function(err, results) {
//  if (err) console.log (err);
  console.log(results);
});

3 个答案:

答案 0 :(得分:0)

不幸的是,递归和回调并不能很好地混合所有这些。在检索到第一个类别后,您正在调用done,但在调用walk之前,您还没有等待对done的其他调用完成。你需要等待他们。我会做这样的事情(伪代码):

fetch this category
    if no subcategories
        call callback with [{ title: ... }] and return
    pending = number of subcategories
    results = [[{ title: ... }]]
    for each subcategory
        recurse
            pending--
            results[index + 1] = subcategory_results
            if none pending
                call callback with the concatenation of the subarrays of results

答案 1 :(得分:0)

node-fibers怎么样?试试这个。

这个链接的好例子:mongo-model example

和方法synchronize util写了咖啡脚本

答案 2 :(得分:0)

好的得到了....需要从内部步行呼叫完成呼叫。

var walk = function(c, done) {
  var results = [];
  Category.findById(c).exec(function(err, cat) {
    if(cat) {
      results.push({ title: cat.title, id: cat.id});
      if(cat.parent) {
        walk(cat.parent, function(err, res) {
          results = results.concat(res);
          done(null, results);
        });
      } else {
         done(null, results);
      }
    } else {
      done('No cat found'); // Error
    }
  });
};
相关问题