Created
November 23, 2015 20:51
-
-
Save moimikey/a33b376f7eb3793e6c47 to your computer and use it in GitHub Desktop.
a callback in javascript for dummies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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