Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS callback error parameter

I'm learning node now and I'm confused about the err parameter. I thought it's supposed to be the first argument of a callback function but I don't see it in many call back functions. Can anyone explain it to me? Thanks!

like image 416
diodeBucks Avatar asked Oct 30 '22 02:10

diodeBucks


1 Answers

There's many different kinds of functions and callback functions in particular. The Node.js standard for callback functions is those of the form:

function(err, arg1, arg2, ...)

Where arg1 and so forth are only present if relevant but the err argument is always first. This is the reverse of a lot of historical JavaScript code where errors would be the last argument.

The Node.js method of forcing the error as the first argument even if there's no error makes ignoring errors harder, you rarely forget to declare that argument, and makes their location predictable.

Now this only applies in the case of a general-purpose callback. That is, there are occasions where calling a function will trigger a singular callback at some point in the future. You'll see them used like this:

doStuff(function(err, successValue) { ... });

There's also the style popularized by jQuery where one or more of your callbacks will be triggered depending on the outcome of the operation:

doStuff({
  success: function(successValue) { ... },
  error: function(err) { ... },
  timeout: function() { ... }
});

Note that in this case you may have both the error and timeout callbacks being fired. You're not obligated to populate all of these, either.

The downside to this approach is the unpredictability of which ones get called and the risk of handling something twice inadvertently.

like image 146
tadman Avatar answered Nov 08 '22 10:11

tadman