pablo86 pablo86 - 4 months ago 8
jQuery Question

JavaScript asyncronous callback error handling

I have a question regarding callbacks, errors and asynchronous functions.
Below we have an example of an asynchronous JS callback that handles errors if there are any. Otherwise it does something with the object received.

doSomething(aThing, function(error, response) {
if (error) {
return handleError(error);
} else if (response) {
return doSomething;
}
});


I imagine that, if there is an error, one of the parameters is an error object and the other one is
null
or
undefined
.

My question is: How does the anonymous callback
function (function(error, response){...})
know that the error parameter is actually an error? What if the callback function would be
function(response, error){...}
?

Answer

That's a common pattern used in NodeJS: Error First Callback

basically, each callback should be called with at least one parameter that indicates wherever there are errors or not...

So, if the first parameter is null you can assume that there are no errors...

var fs = require('fs');

fs.readFile("somefile.txt", function(err, data) {
  if(err) {
    console.log('We have some error', err);
    return;
  }
  
  //do something with your data
  console.log('success', data);
});