Created
March 30, 2016 09:24
-
-
Save pragyanatvade/82101c4da9610f3d73529087fb55a995 to your computer and use it in GitHub Desktop.
Recursion pattern in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CategorySchema.statics.getLineage = function (categoryId, flag, done) { | |
var self = this; | |
var count1 = 0; | |
var count2 = 0; | |
var recurse = function (id, results) { | |
var deferred = Promise.defer(); | |
self.findById(id, function(error, category) { | |
if (error) { | |
deferred.reject(); | |
} else { | |
if (!_.isEmpty(category.children)) { | |
var iterator = function (child, next) { | |
recurse(child, results) | |
.then(function () { | |
deferred.resolve(); | |
}); | |
next(); | |
}; | |
async.each(category.children, iterator, function (error) { | |
if (error) { | |
deferred.reject(); | |
} | |
}); | |
} else { | |
var interval = setInterval(function () { | |
if (count2 < count1) { | |
count2 = count1; | |
} else { | |
deferred.resolve(); | |
clearInterval(interval); | |
} | |
}, 100); | |
count1++; | |
if (flag) { | |
results.push({"category": category._id}); | |
} else { | |
results.push(category._id); | |
} | |
} | |
} | |
}); | |
return deferred.promise; | |
}; | |
var latestGen = []; | |
recurse(categoryId, latestGen) | |
.then(function () { | |
done(null, latestGen); | |
}) | |
.catch(function (error) { | |
done(error); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment