0

I am learning javascript callback or higher order functions. Please help me in understanding the mistake in the following functions. I am trying to call more than function as callback functions. Is it not allowed?

My code is:

var firstFunction = function(item1){
    console.log("calling firstFunction");
    console.log(item1);
}
var secondFunction = function(item2, f1){
    console.log("calling secondFunction");
    f1(item2);
}
//secondFunction("first", firstFunction);

var thirdFunction = function(item3, f2,f1){
    console.log("calling thirdFunction");
    f2(item3);
}

thirdFunction("second", firstFunction, secondFunction);
Sreekumar R
  • 573
  • 6
  • 24

3 Answers3

0

What you did is correct, But you have to pass f1 as a call back in third function

var thirdFunction = function(item3, f2,f1){
    console.log("calling thirdFunction");
    f2(item3, f1);
}
Raja Sekar
  • 2,062
  • 16
  • 23
0

Your code is okay, there are no restrictions as for callback depth, but be awared of stack overflow errors.

In your code you are executing firstFunction inside third one, after that script stops. I suppose to think that you wanted to execute secondFunction inside the thirdFunction and then first inside the second:

function firstFunction (item){
    console.log("calling firstFunction");
    console.log(item);
}

function secondFunction (item, f1){
    console.log("calling secondFunction");
    f1(item);
}

function thirdFunction (item, f1,f2){
    console.log("calling thirdFunction");
    f2(item,f1);
}

thirdFunction("second", firstFunction, secondFunction);

that code would work in described way.

Artem Lopatiy
  • 948
  • 5
  • 15
0

Please have a look at this script

var firstFunction = function(item1, f2) {
  document.body.innerHTML += item1 + " | This is firstFunction <br/> ";
  //console.log("calling firstFunction");
  f2(item1, secondFunction);
}
var secondFunction = function(item2, f1) {
  document.body.innerHTML += item2 + " | This is  secondFunction <br/> ";


}


var thirdFunction = function(item3, f1, f2) {
  document.body.innerHTML += item3 + " | This is thirdFunction <br/> ";
  f1(item3, f2);

}

thirdFunction("chain started third function", firstFunction, secondFunction);
<html>

<body></body>

</html>
Asim Khan
  • 572
  • 6
  • 34