0

I am trying to preload arguments into a callback function. Here's a stripped down example of what I'm attempting.

function doSomething(callback) {
  // code to obtain a 3rd argument, eg API call or access a file.
  // let's say we are getting the number 5.
  const c = 5;
  // invoke the callback with its final argument.
  callback(c);
}

function toBeCalled(arg1, arg2, arg3) {
  // do a calculation with these arguments.
  console.log((arg1 * arg3) + arg2);
}

// invoke doSomething with the first two arguments already defined.
// eg user input.
doSomething(toBeCalled(a, b));

what I want to happen:

doSomething(toBeCalled(4, 2));

console: 22

I've given the callback its first two arguments when I invoke doSomething. doSomething grabs the value of the third argument from somewhere and invokes the callback with the 3rd value added.

what actually happens:

As far as I'm aware the code above would invoke toBeCalled too early which is causing the error:

TypeError: callback is not a function

Thank you for any help!

Nick Ramsbottom
  • 583
  • 1
  • 6
  • 17

1 Answers1

1

Just wrap it in another function:

f = function (c) {
        toBeCalled(4, 2, c)
    } 

Then pass f as the callback to receive the final argument:

doSomething(f)
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117