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);
});
Unfortunately, recursion and callbacks don't mix all that nicely. You're calling done after retrieving the first category, but you're not waiting for the other calls to walk to complete before calling done. You need to wait for them. I'd do something like this (pseudocode):
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
how about node-fibers? try this.
Good example like this link : mongo-model example
and method synchronize util written coffee-script
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
}
});
};