Is this a bad practice?
Yes. http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
How would you design the api with this example?
Instead of passing a callback to validate
that handles whether it was called asynchronously or not, you should just make the validate
function always asynchronous:
function validateAll(docs) {
async.eachSeries(docs, validate);
}
function validate(doc, callback) {
if (doc.sum < 10) {
process.nextTick(function () {
callback(new Error("Invalid sum"));
});
} else if (doc.otherDocumentId) {
validateOtherDocFromDbAsync(doc.otherDocumentId, callback); // collection.find() or something
} else {
process.nextTick(callback);
}
}