skip to Main Content

I have a function

 await mainFunction(function1, function2, function3)

I also want to pass multiple functions into the mainFunction

const mainFunction =   async (function1, function2, function3) =>  async ({ param1, param2, param3}) => {

const params = { param1, param3, param3};

How do I do this without passing it as another param?

3

Answers


  1. If I understand you right, you want to pass indefinite number of arguments to your main function, so you can use the ...rest parameter.

    The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript. (from MDN)

    Note. You can call the rest parameter whatever you want.

    So in your code it will look something like this:

    const mainFunction = async (...functions) => {
      // DO SOMETHING WITH THE PARAMS ARRAY
    }
    

    You can read more about it here:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

    Login or Signup to reply.
  2. You can try using Rest parameters (...) that allows to pass any number of functions as an array:

    const mainFunction = async (...functions) => {
      const params = { param1: value1, param2: value2, param3: value3 };
    
      //loop through functions and call them
      for (const func of functions) {
        await func(params);
      }
    };
    
    Login or Signup to reply.
  3. if you want to maintain your current syntax you can do it like this

    const mainFunction = (function1, function2, function3) => async ({ param1, param2, param3 }) => {
      const params = { param1, param2, param3 };
      console.log(params);
      await function1(param1);
      await function2(param2);
      await function3(param3);
    };
    
    const function1 = (param) => console.log('function1', param);
    const function2 = (param) => console.log('function2', param);
    const function3 = (param) => console.log('function3', param);
    
    const paramsObject = {
      param1: 'Value 1',
      param2: 'Value 2',
      param3: 'Value 3',
    };
    
    const innerFunction = mainFunction(function1, function2, function3);
    innerFunction(paramsObject);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search