Nested Callbacks

The window object represents an open window in a browser.
The window object has a built-in method called setTimeout.
This method will execute a callback function (or evaluate an expression) after a specified number of milliseconds.
Here is an example using a Named Function.

function myCallbackFunction() { 
   console.log("callback");
}
window.setTimeout(myCallbackFunction, 1000);

Here is the same code using an Anonymous Function.

window.setTimeout(function() { 
   console.log("callback");
}, 1000);

Nested Callback Syntax

This nesting or indentation is often called the "Pyramid of Doom".

setTimeout(function() { 
   console.log("one");
   setTimeout(function() {
      console.log("two");
      setTimeout(function() {
         console.log("three");
      }, 1000);
   }, 1000);
}, 1000);

Continuation Passing Style Syntax

This syntax is where the control is passed explicitly in the form of a continuation.

function fun_one(callback) { 
   console.log("one");
   setTimeout(callback, 1000);
}
function fun_two(callback) {
   console.log("two");
   setTimeout(callback, 1000);
}
function fun_three() {
   console.log("three");
}

fun_one(function() {
   fun_two(fun_three);
});

Problem with Callbacks

The problem with callbacks is not actually related to the indentation or the syntax used.
When you are calling built-in functionality, for example setTimeout, we can assume the callback will be executed correctly.
However if we are calling or using third party code, can cannot always assume the callbacks will be executed correctly.
This problem is known as "Inversion of Control" and means that you have handed control of your code over to a third party library.
We cannot always trust third party libraries to execute the callback(s) correctly.


© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext