I’ve been reading Callback Hell, which states:
With callbacks the most popular way to handle errors is the Node.js style where the first argument to the callback is always reserved for an error.
and gives this example:
var fs = require('fs')
fs.readFile('/Does/not/exist', handleFile)
function handleFile (error, file) {
if (error) return console.error('Uhoh, there was an error', error)
// otherwise, continue on and use `file` in your code
}
My functions look differenty, something like ths
function example (varA, varB){
//...
try{
//...
}catch {
//...
}
}
where varA and varB are variables/arguments used to do stuff inside the function. Now, if I would change the code to function example (error, varA, varB)
, how would I pass the variables, since the first expected argument is actually an error.
If anyone can please provide an example or/and provide some good reading it would be most welcome.
Thank you
2
Answers
I’m assuming you mean that you’re writing an API that will accept callback functions with that kind of signature. If so, on success you call it with
null
as the first parameter, as that’s the convention in these callback-style APIs. (And on failure you’e call it with an error as the first parameter, and typically no other parameters.)But asynchronous callback-style APIs of this kind are obsolete. Instead, use promises, directly or indirectly via
async
functions.It depends of what you want.
In that case you pass the err to the calling code, cuz it is common contract.
Callback uses for async operations. These operation can be finished with error and first err argument is a common way to say you "we have a problem"