Skip to content

Instantly share code, notes, and snippets.

@rjcorwin
Created January 30, 2014 17:11
Show Gist options
  • Select an option

  • Save rjcorwin/8713632 to your computer and use it in GitHub Desktop.

Select an option

Save rjcorwin/8713632 to your computer and use it in GitHub Desktop.

Callback Hell

Callbacks are rampant in Javascript, this can cause what's known as "Callback Hell", or as I like to call. Rat nests. In the following example the "rat nest" is not that hard to follow along with, and that will be the case when your program is simple. But imagine when your program grows to have many rat nests, perhaps even the rat nests become intertwined. Messy.

/*
 * Callback hell example
 */

function yell(text, callback) {
	alert(text)
	callback()
}

yell('First yell', function() {
	yell('Second yell', function() {
		yell('Third yell', function() {
			alert('All done!')
		})
	})
})
/*
 * Shallow code example
 */

function yell(text, callback) {
	alert(text)
	callback()
}

function one() {
  yell('First yell', two)
}

function two() {
  yell('Second yell', three)
}

function three() {
  yell('Third yell', four)
}

function four() {
	alert('All done!')
}

// Start
one()

A note on the importance of synchronous operations in Javascript

When you do an HTTP operation you can do other things in a synchrounous fashion. This is the case because if every time Javascript ran a HTTP request and "blocked" while waiting for the return, the entire browser would freeze between request and returns. This would result in a jittery exerience, thus the need for callbacks from the very early days of ECMA script.

While sychronous operation is cool, it can be very difficult to manage in an asyncrounous way when the order of operations really matter. The above example is one method to control the flow of your operations while maintaining readability.

This gist is inspired by http://callbackhell.com/

@henboffman
Copy link
Copy Markdown

If you want to avoid using callbacks altogether, you can use promises as well:

function yell(text) {
    alert(text)
}

function one() {
  yell('First yell')
}

function two() {
  yell('Second yell')
}

function three() {
  yell('Third yell')
}

function four() {
    alert('All done!')
}

// Start
var promise = one();
promise.then(two().then(three().then(four())));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment