3

I have the following piece of code:

function fun1(callback){
  var result =  "result of function 1";
  callback(result)
};
function fun2(callback){
  var result =  "result of function 2";
  callback(result)
};

fun1(log); // displays "result of function 1"
fun2(log); // displays "result of function 2"
fun2(fun1(log)); // Type Error ...

Where log is simple function (i.e. console.log(data)...) I'm wondering why fun2(fun1(log)) does not display "result of function 1" as one would expect. What is missing? Many thanks - Christian

1 Answer 1

2

fun2 expects to get a function. what you gave is the result (which is 'undefined') of func1. meaning

var something = fun1(log);
fun2(something);

So not sure what you expect to do in fun2 but you need to provide a callback and not undefined.

you could do:

function fun1(callback){
  var result =  "result of function 1";
  callback(result)
  return callback
};
function fun2(callback){
  var result =  "result of function 2";
  callback(result)
};

fun1(log); // displays "result of function 1"
fun2(log); // displays "result of function 2"
fun2(fun1(log));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Sagie for your quick response. Is this the standard way of doing when you want to chain functions together?
there are many ways to chain functions, for example to return a function, to use promise and so on... there is no 1 specific standard way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.