Callback Hell: A guide to writing asynchronous JavaScript programs

<span class="keyword">var</span> photo <span class="keyword operator">=</span> <span class="function call">downloadPhoto</span>(<span class="string">'http://coolcats.com/cat.gif'</span>)
<span class="comment">// photo is 'undefined'!</span>

In this case the gif might take a very long time to download, and you don’t want your program to pause (aka ‘block’) while waiting for the download to finish.

Instead, you store the code that should run after the download is complete in a function. This is the callback! You give it to the downloadPhoto function and it will run your callback (e.g. ‘call you back later’) when the download is complete, and pass in the photo (or an error if something went wrong).

<span class="function call">downloadPhoto</span>(<span class="string">'http://coolcats.com/cat.gif'</span>, handlePhoto)

<span class="storage function">function</span> <span class="entity name function">handlePhoto </span>(error, photo) {
  <span class="keyword">if</span> (error) console.<span class="function call">error</span>(<span class="string">'Download error!'</span>, error)
  <span class="keyword">else</span> console.<span class="support method">log</span>(<span class="string">'Download finished'</span>, photo)
}