G D G D - 2 months ago 12
Javascript Question

Anonymous callback functions

So, I understand callback functions to a degree. For instance, I completely understand this:

function finalGuy(x) {
alert("Final Number: " + x);
}

function secondGuy(x, callback) {
x = x - Math.sqrt(x);
callback(x);
}

function firstGuy(callback) {
var x = parseInt(prompt("Enter a number"));
x *= x;
secondGuy(x, callback);
}


firstGuy(finalGuy);


However, when faced with something like this I can't seem to grasp it.

a(function () {
b(function () {
c()
})
});


Can someone please translate the first sequence of callbacks into a working example like the second one? Specifically, passing one result to the next callback similarly to how I did it in the first example.

Answer

These two produce the same result

1.

function acceptCallback(callback) {
  callback();
}

function callback() {
  console.log('callback invoked');
}

acceptCallback(callback); // => 'callback invoked'

2.

function acceptCallback(callback) {
  callback();
}

acceptCallback(function() {
  console.log('callback invoked');
});

In the first example you pass a function declaration, in the second example you pass an anonymous function

3. Performing operations in the scope of a callback to be passed to another callback, aka "callback hell"

Nothing special here, it's the same syntax as the first two examples. This is difficult to read for anyone.

function first(callback) {
  callback('from first');
}

function second(callback) {
  callback('from second');
}

function third(callback) {
  callback('from third');
}

function fourth(n, callback) {
  callback(n * 10);
}

first(function(fromFirst) {
  var a = 5;
  console.log(fromFirst); // 'from first'
  second(function(fromSecond) {
    console.log(fromSecond); // 'from second'
    third(function(fromThird) {
      console.log(fromThird); // 'from third'
      var b = a + 5; // 10
      fourth(b, function(fromFouth) {
        console.log(a, b, fromFourth); // 5, 10, 100
      })
    });
  });
});
Comments