Async - callbacks
example of simple callback useage
function cbFunc() {
console.log("this is the callback function that is run after 'cbExample' is done with its main code block);
}
function cbExample(something, cb) {
let somethingElse = something + 2
cb();
}
cbExample(5, cbFunc);
example with anomalous arrow funcs
function cbExample(something, cb) {
let somethingElse = something + 2
cb();
}
cbExample(5, () => {
console.log("this is the callback);
});
callbacks and async useage
many filesystem utilities in nodeJS take a callback as an option, that function you give it in the callback is then executed after the filesystem utility completes its function. This allows you to take some action on say a file after it has been opened.
problem with callbacks
A single function with a callback is easy to see and understand but often times a function with a callback has to be called inside another callback etc. This can lead to deeply nested callbacks and indentation that quickly becomes hard to read.
Next Article: promises