Javascript - Callback

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

callbacks in Javascript.

It is the primary method of enabling asynchrony.

Advertising

3 - Example

3.1 - Without argument

callback = function () {
   console.log("Hello Callback");
}
 
function highOrder(callbackFunctionToCall){
  // Call the callback function
  callbackFunctionToCall();
}
 
highOrder(callback);

3.2 - 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 call back function with an argument that returns an Hello
callback = function (who) {
   return "Hello "+who;
}
  • The High order function that expects a function as 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");
  }
);

4 - 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);
                 }
             }
         }
     }
}
Advertising
web/javascript/es/callback.txt · Last modified: 2019/02/16 17:40 by gerardnico