Hopefully this is not too abstract but I am looking for advice on expected behavior when creating a Node module API. I am finding that in my module implementation, checking to make sure the caller has provided a callback before I call it is getting messy. I am starting to think its user error to not provide a callback for an API that clearly needs one to do its job.
Being a Node beginner, what is the general pattern for modules? I took a look at the Node source code itself. It seems like in some places they use a function that swaps an unsupplied callback with a generic one that throws an error. This seems like it might lead to confusion though.
Thanks
You can provide a default callback. Depending of your needs and the importance of the callback, you can provide a noop function or just a function that only check if there was any error.
if (!callback) {
callback = function noop() {}
}
Throwing or showing the error you'll decide. (Better to not throw most cases)
if (!callback) {
callback = function handleError(e) {
if (e) console.log(e);
// Or
if (e) throw(new Error(e))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With