Skip to content

Latest commit

 

History

History

Callback Hell

What is going on!? My thoughts exactly. You've just been dragged through Callback Hell, a friendly name to define deeply nested and indented callbacks, on top of some more callbacks, which make it pretty difficult to follow the flow, and understand what's going on.

callback-hell.jpg

In this series of examples, I go over the different ways in which you can reduce the hell in your async JavaScript. Concretely, this should help you reduce indent levels and also result in clearer code that's easier to read.

Behold, callback hell in all its gory glory.

(function () {
  var loaded;
  function init () {
    document.body.addEventListener('click', function () {
      console.log('Clicks are important.');
      handleClick(function (data) {
        if (data) {
          return processData(data, function (copy) {
            copy.append = true;
            done(copy);
          };
        } else {
          reportError(function () {
            console.log('data processing failed.', err);
          });
        }
      });
    });
    function done (data) {
      loaded = true;
      console.log('finished', data);
    }
  }
  init();
})();

The numbered files that can be found in this directory are explained in the book as a series of steps you'd take to get in and out of callback hell.