And why they are awesome!
Perform time consuming tasks
Fetch from database
Fetch from API
Callbacks
Function to be called once done
function readFromFileOrSomething(cb) { // Perform read operations cb(err); }
Send errors or null to callback
readFromFileOrSomething(function(err) { if (err) { console.log('Uh oh!'); } })
function deepFunction() { createPerson(function(employee) { createRestaurant(function(restaurant) { createEmployeeRegister(function(register) { register.addEmployee(employee, function() { restaurant.addRegister(register, function() { restaurant.notifySomeone(function() { console.log('Done!'); }); }); }); }); }); }); }
// Looks harmless function addEmployee(employee, restaurant, register, cb) {}
Add null
// Won't work! addEmployee(employee, function() {}) // Works but looks like crap addEmployee(employee, null, null, function(){ /* code here */});
Alternatives?
// Define cb first! function addEmployee(cb, employee, restaurant, register) {} // Provide cb-function first! addEmployee(function() { // Do stuff }, employee, null, null) // Not very readable
funcThatTakesCallback(function(err) { if (!err) { otherTaskThatTakesCallback(function(err) { if(!err) { console.log('Done!'); } else { handleError(); } }); } else { handleError(); } });
Add error handling to the deepFunction() 😱
Part of ES6 (EcmaScript 2015)