Calling a function which is inside a exported function (Node.js)

Viewed 43

In a Node/Next.js environment, I have a utility function exported like this:

export async function MyFunction(one, two, three) {
    var a, b

    // do some logic / save to context store, etc.

}

and I'm using it inside my pages/components like MyFunction("one",false,"three") , if I now have a inner function like:

export async function MyFunction(one, two, three) {
   var a, b

   function MySecondFunction(){
      a = 'a new value'
      b = 'b new value'
      // update some context stores
   }

   // do some logic / save to context store, etc.

   if(...){
      MySecondFunction()
   }

}

how can I run MySecondFunction() from outside (from my pages/components)? I found some examples but it all imply to return, the difference is here I don't have to return anything from either MyFunction or MySecondFunction

EDIT: to give more context, MySecondFunction() is a sort of "reset" of all the stores and variables set within MyFunction(). As a store management library I'm using Zustand, and I'm loading various stores, so I was wondering if I can call this "reset" (MySecondFunction) from the outside without having to require all the stores again in each component from which I'm willing to do the reset.

1 Answers

You can also return the second function.

export async MyFunction(one, two, three) {
  // do some logic

  function MySecondFunction(four, five, six) {
    // do more logic
  }
  
  // execute the second function from inside MyFunction (can be omitted)
  // MySecondFunction()

  // return the second function to be able to run it at a later time from outside.
  return MySecondFunction
}

//call just the first function
MyFunction("one", "two", "three");

//run the second function right after the first function
MyFunction("one", "two", "three")("four", "five", "six");

// if you want to execute the second function at a later time, you can execute MyFunction 
// and assign its return value (which is MySecundFunction) to a variable and execute it later.
let mySecondFunction = MyFunction("one", "two", "three");
mySecondFunction("four", "five", "six");

I hope this is what you mean.

Related