Understanding nested callbacks

Hey guys, beginner here trying to wrap his head around nested callbacks.

On this MDN page, there is an example given of how chaining several asynchronous functions together would (in the past) require this infamous callback pyramid of doom:

doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
  console.log('Got the final result: ' + finalResult);
}, failureCallback);
  }, failureCallback);
}, failureCallback);

Allright so I’m just trying to wrap my head around this and I can’t let it go.

As far as I can understand, I’m looking at a doSomething Higher Order function call, which has an (anonymous) callback function declared as its parameter, which in turn contains a second function call doSomethingElse(), which has another (anonymous) callback function declared as a parameter, containing a call to a third function doThirdThing… and so on.

In short, there are three nested function calls here: doSomething(), doSomethingElse() and doThirdThing(). Each of these has an anonymous function declared as an input parameter.

In order to grasp how this would work, I’ve tried to code my own “pyramid of doom”, without any parameters of failure callbacks to keep it simple:

function someThing() {
	console.log("Do Something!");
}

function someThingElse () {
  console.log("Do Something Else!");
}

function doThirdThing () {
  console.log("Do Third thing!");
}

someThing(function(){
  console.log("First anonymous callback!");
  someThingElse(function(){
    console.log("Second anonymous callback!")
    doThirdThing(function() {
      console.log("Third anonymous callback!");
    })
  })
})

When I run this code, all that is being printed to the console is: Do Something!

I cannot understand why someThingElse and doThirdThing are not being run, nor any of the anonymous callback functions??

What am I missing here? Please help!

:upside_down_face:

You’re passing the functions as parameters but not actually calling the passed functions within each. Here’s the code with some changes to demonstrate:

function someThing(fn) {
  console.log("Do Something!");
  fn();
}

function someThingElse (fn) {
  console.log("Do Something Else!");
  fn();
}

function doThirdThing (fn) {
  console.log("Do Third thing!");
  fn();
}

someThing(function(){
  console.log("First anonymous callback!");
  someThingElse(function(){
    console.log("Second anonymous callback!")
    doThirdThing(function() {
      console.log("Third anonymous callback!");
    })
  })
})

Hope this helps.