return value from a function inside a module

186 Views Asked by At

I have created a module like the following:

module.exports = function() {

  function func1 () {

  }

  function func2 () {

  }

  return function() {

    func1();
    func2();

    return value;

  };
}

when I call the module in another file

myModule = require('myModule')

use the module

myModule() I get an undefined value. what do I wrong?

2

There are 2 best solutions below

2
On BEST ANSWER

You're exporting a function that when called returns another function which in turn will throw an ReferenceError saying that value is undefined which you can alleviate by defining value.

return function() {

    func1();
    func2();

    return 1; //for example

  };

In order to run it you need to call it twice.

myModule()();
>> 1

My guess is that you just want the value returned so wrap it in an IIFE

module.exports = function () {
    return (function() {
        func1();
        func2();

        return 1; //for example
    })();
}
0
On

If you expect myModule() to return a value you can export IIFE:

module.exports = function () {

    function func1() {

    }

    function func2() {

    }

    return function () {
        func1();
        func2();
        return value;
    }();
}