-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().

1
  • 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. Commented Oct 21, 2020 at 15:31

2 Answers 2

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
});
Sign up to request clarification or add additional context in comments.

9 Comments

what if fn1() has paramters too? Sorry should've mentioned that in my question
Then you need to put those in the (): param3(1, 2)
@nb_nb_nb If it accepts, say, 1 and 2, then I'd pass: () => fn1(1, 2) (if they're defined in the caller, but not in the fn2 section)
@Barmar, inside param3()?
@nb_nb_nb It depends where the parameters need to be defined. If inside fn2, then use the code in the answer but pass the parameters to param3. If outside fn2, then () => fn1(1,2) as the parameter passed to fn2.
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.