CALLBACKS

Callback patterns control the flow of execution on an application. A callback function is passed as a callback in another function. Function receiving callback runs the callback upon execution. Event listeners is an example of a callback common in javascript.

// A function that takes a callback //
function doSomething(callback) {
console.log('I did something!');
callback();
}

// passing a callback //
doSomething(function() {
console.log('Something done! Let us move on!');
});
//event listener. When an event occurs, a callback function executes
$('#form-signup').on('click', function (event) {
event.preventDefault();
var user = _.object($("#form-signup").serializeArray().map(function (v) {
return [v.name, v.value];
}));
userService.signUp(user);
});

ERROR FIRST CALLBACKS

In an error first callback, an error object is taken as the first argument (if an error occurred, the first error argument will return the error). The second argument is for any successful response data (if no error occured, err is set to null successful response data is returned in second argument).

The fs.readFile() method takes in a file path and calls a callback when file path has been read through. If no err occurs, the file’s contents are returned in the data argument. If an err occurs, an error object populated with why an error occurred is returned in the first argument.

fs.readFile('/foo.txt', function(err, data) {
// If an error occurred, handle it (throw, propagate, etc)
if(err) {
console.log('Unknown Error');
return;
}
// Otherwise, log the file contents
console.log(data);
});