Table of Contents

About

This page is about callbacks in Javascript.

It is the primary method of enabling asynchrony.

Example

Without argument

callback = function () {
   console.log("Hello Callback");
}

function highOrder(callbackFunctionToCall){
  // Call the callback function
  callbackFunctionToCall();
}

highOrder(callback);

With argument

With argument, you are not passing the function but the return value of the function. You need then to wrap it up in a anonymous function.

Example:

  • The callback function with an argument that returns an Hello
callback = function (who) {
   return "Hello "+who;
}
  • The High order function that expects a function as an argument
function highOrder(callbackFunctionToCall){
  // Call the callback function
  console.log(callbackFunctionToCall());
}
  • The call of the highOrder needs then to wrap the callback function in a anonymous function because callback(“Nico”) is not a function but the returned value (ie Hello Nico)
highOrder( 
   function() {
      return callback("Nico");
  }
);

Pyramid of doom

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
      console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

getData( a => {
     getMoreData(a, b => {
         getMoreData(b, c => {
             getMoreData(c, d => {
                 getMoreData(d, e => {
                     console.log(e);
                 }
             }
         }
     }
}