Skip to content

Instantly share code, notes, and snippets.

@moimikey
Created November 23, 2015 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/a33b376f7eb3793e6c47 to your computer and use it in GitHub Desktop.
Save moimikey/a33b376f7eb3793e6c47 to your computer and use it in GitHub Desktop.
a callback in javascript for dummies
// callbacks != promises
function doSomeAction() {
return true
}
function appleTree() {
return doSomeAction()
}
appleTree()
// --------------------------------------------------------------------
// we can decouple `doSomeAction` from `appleTree` by using a callback.
// it will provide more control over the execution flow.
function doSomeAction() {
return true;
}
// instead of calling `doSomeAction` from within `appleTree`, we can decouple
// by completely removing the call to `doSomeAction`, and instead take a
// parameter (which will be a function [our callback]) that will be executed
// instead.
function appleTree(cb) {
if (typeof cb === 'function') return cb() // make sure it's a function
return false // no function? don't bother executing anything then. there is no callback to call.
}
appleTree(doSomeAction) // i can pass an arbitrary function method now. it's not dependent on `doSomeAction`
// or
appleTree(function() { // anonymous function style
doSomeAction()
})
// or
appleTree.call(null, doSomeAction) // or using `call`
// --------------------------------------------------------------------
// a potential bottleneck of callbacks, dubbed 'callback hell,' refers
// to relying heavily on nested callbacks. it is in this case that it may
// make more sense to use an alternative form of async control; this may
// include concepts like event buses (event emitters), signals and as
// mentioned briefly, promise-based callbacks (promises).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment