Is it possible to call two functions at the same time with one set of arguments?

3.6k Views Asked by At

Out of curiosity, is it possible to call two functions at once?

For example, here is some pseudo code:

// custom logging function:
function custom_log(string) {
  console.log(string);
}

(console.log && custom_log)("Hello World.");

If it's possible how?

2

There are 2 best solutions below

0
IceMetalPunk On BEST ANSWER

No, you can't say "here are two functions, here's one set of arguments, call them both with the same arguments". But you can pre-define the arguments in a variable and pass that to both functions, which is probably the most concise if you use object destructuring for your parameters:

function custom_log({output, errorVal}) {
  console.log(output);
  console.error(errorVal);
}
const args = {
    output: 'Hello, world',
    errorVal: 'Some error happened'
};
console.log(args);
custom_log(args);

You could also just create a helper function that iterates through an array of passed functions and calls them all:

function callAllWith(functionList, ...args) {
   functionList.forEach(fn => fn(...args));
}
callAllWith([console.log, custom_log], 'Hello, world!');
0
Bergi On

Not "simultaneous" in any parallel-processing sense, no.

But yes, you could easily write a higher-order function that takes multiple functions and creates a new one that you need to call only once:

function atOnce(...fns) {
    return function(...args) {
         for (const fn of fns)
             fn.apply(this, args);
    };
}

atOnce(console.log, custom_log)("Hello World");