Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use function before initializing within module.exports

I have two functions the first is register which uses a function called emailExists and both functions are exported using

// services.js
module.exports = {
async register(prm) { emailExists(prm) // emailExists is not defined  },
async emailExists(prm) { // do something } 
} 

I have a couple of questions
should I use a class that contains all the methods in the services layer
or that’s not a best practice to use a class for the services layer
or should I declare the functions and then exporting?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have various choices:

  • use the this keyword (doesn’t work if the require()d module is destructed):

    module.exports = {
      async register(prm) { this.emailExists(prm) },
      async emailExists(prm) { /* do something */ },
    };
    
  • refer to the method as part of module.exports:

    module.exports = {
      async register(prm) { module.exports.emailExists(prm) },
      async emailExists(prm) { /* do something */ },
    };
    
  • declare local functions up-front, then export them:

    async function register(prm) { emailExists(prm) }
    async function emailExists(prm) { /* do something */ }
    module.exports = { register, emailExists };
    

No, you should not use a class unless you actually need multiple different instances.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading