0

What's wrong in the following callback function example? I am passing some parameters and in the end, I am passing a function that must automatically run when the other tasks are done. So, why am I getting an error?

Expectation:

I expected 2 console.logs. First giving output of a, b, a+b and second console printing hello.

Example:

function alpha(a, b, ()=>{
  console.log("hello");
}){
  console.log(a, b, a+b);
}
alpha(5, 10);
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • 1
    _"I am passing a function..."_ - No you're "defining" a function with 2 parameters and an anonymous function without a parameter - which is invalid syntax. – Andreas Jul 22 '20 at 14:43
  • @Andreas - correct it with code? will be helpful! – Deadpool Jul 22 '20 at 14:44
  • There's already an answer (+ [How to explain callbacks in plain english? How are they different from calling one function from another function?](https://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o)) – Andreas Jul 22 '20 at 14:46
  • @Andreas - this means even if I can pass 3 functions as parameters and then I call all 3 one after another in parent function, so will this mean this function has 3 callback functions? – Deadpool Jul 22 '20 at 14:51
  • 1
    It has three parameters that, if you pass actual functions, would be called _"one after another"_. Every function you pass as argument for one of the parameters would be a "callback". That setup would be quite unusual, normally there is only one "callback". – Andreas Jul 22 '20 at 17:35

2 Answers2

1

Here is what you want:

function alpha(a, b, fn) {
    console.log(a, b, a + b);
    fn();
}
alpha(5, 10, () => {
    console.log("hello");
});

// or defined by default
function alpha2(a, b, fn = () => {
    console.log("hello");
}) {
    console.log(a, b, a + b);
    fn();
}
alpha2(5, 10);
8HoLoN
  • 1,122
  • 5
  • 14
1

You might be looking for something like this, with passing parameters to callback function:

function alpha(a, b, f = (a,b) => a+b) {
    return f(a,b);
}

const multiply = (a,b) => a*b
console.log(alpha(5, 10));
console.log(alpha(5, 10, multiply));
Jacek Rojek
  • 1,082
  • 8
  • 16