Javascript - Callback

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);
                 }
             }
         }
     }
}





Discover More
Model Funny
Function - Callback function

A callback function iscalled back by the higher-order function that takes it as parameter. Callbacks is a method of enabling asynchrony (asynchronous operation). A callback is a function that is passed...
Browser
How to select text dynamically in a Browser with Javascript? The window Selection Object explained

How to manipulate the selection made by a mouse or with the keyboard in a browser
Javascript - Asynchrony

This page is Asynchrony in javascript. Asynchrony is not only critical to the performance of our applications, but it’s also increasingly becoming the critical factor in writability and maintainability....
Javascript - Promise Chaining

promise chaining is one of the two promise syntax to manipulate promise The promise function addOne that will add one. The chain The creation of a promise is done via a constructor that...
Devtool Chrome Event Listener
What is the selectstart DOM event with examples and howto's in Javascript?

selectstart is a selection event that occurs when the user agent (the browser used by the user mostly) is to associate a new range to a selection object Note that when the user clicks on: a text,...



Share this page:
Follow us:
Task Runner