Recursive callbacks

Recursive callbacks

Problem

Need a little help trying to get this breadcrumb builder working – it’s a recursive fetch for parent categories that should return an array of entries. Not quite working and my brain is fried…. currently only returns the last entry.

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);
});
Problem courtesy of: Yashua

Solution

Okay got it…. Needed to call done from the inner walk call.

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
    }
  });
};
Solution courtesy of: Yashua

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *