It's common to validate arguments and return error in functions.
However, in JavaScript callback function, such as:
function myFunction(num, callback) {
if (typeof num !== 'number') return callback(new Error('invalid num'))
// do something else asynchronously and callback(null, result)
}
I wrote a lot of functions like this, but I wonder if there's something potentially harmful. Because in most cases, the caller assumes this is an asynchronous function and the callback will execute after the code right after the function call. But if some arguments are invalid, the function will immediately call the callback. So the caller must be careful dealing with the situation, that is, an unexpected execution sequence.
I want to hear some advice on this issue. Should I carefully assume that all asynchronous callbacks may be executed immediately? Or I should use something like setTimeout(..., 0) to convert synchronous thing to asynchronous one. Or there's a better solution I don't know. Thanks.