-1

I have a 2 functions:

const fn1 = (1, 2) => {
   //do something
}
const fn2 = ({param1, param2, param3}) => {
   $(`#id_one`).text(param1);
   $(`#id_two`).text(param2);
   param3;
}

Calling functions:

fn2({
   param1: 'hello',
   param2: 'world',
   param3: fn1(1, 2)
});

When I call the function above, fn1() is getting called before fn2(). Why is that happening? I need to go through fn2() before fn1().

nb_nb_nb
  • 1,243
  • 11
  • 36
  • It happens because `fn1()` has to be resolved in order to assign the property to `param3` which is needed in order to create the object, which is passed to `fn2`. It's all nested. It would perhaps be clearer if you explain why is it a problem that `fn1` doesn't need to be called and what you're trying to do in general. – VLAZ Oct 21 '20 at 15:31

2 Answers2

3

() after an identifier that points to a function invokes the function. Since you want to invoke the function after everything in f2 is done, put the ()s inside fn2, not in the caller:

const fn2 = ({param1, param2, param3}) => {
   $(`#id_one`).text(param1);
   $(`#id_two`).text(param2);
   param3();
}
fn2({
   param1: 'hello',
   param2: 'world',
   param3: fn1
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You need to pass the callback function into fn2 like this:

fn2({
   param1: 'hello',
   param2: 'world',
   param3: fn1
});

and call fn1 from fn2 like this:

const fn2 = ({param1, param2, param3}) => {
   $(`#id_one`).text(param1);
   $(`#id_two`).text(param2);
   param3();
}

Whenever you use the parentheses, the function is immediately invoked.

What you're currently dong param3: fn1() is saying "param3 is equal to the return value of this function" and it runs fn1() to get the return value, even if the function doesn't return anything.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34