0

I see different ways coders writing a module.exports function.

1st:

module.exports = function() {
  return (async () => {

  })()
}

2nd:

module.exports = async () => {

}

What is the difference in 1st way and 2nd way?

And what is the need of returning an async () function in already defined function, in first way. And in 2nd way we are not calling the function as we did in 1st way.

Can anyone help me understand this concept. I am very new to Javascript

Estus Flask
  • 206,104
  • 70
  • 425
  • 565

2 Answers2

0

Snippet 1 is regular function that uses IIFE and snippet 2 is arrow function. Both are functions that return promises because async is syntactic sugar for promise-returning function.

IIFEs are commonly used to prevent the leakage of `variables to global scope. This is not a concern in Node because the code is executed in module scope.

The use of IIFE is less justified in ES6 because there are block-scoped variables to prevent the leakage. IIFE in snippet 1 is not justified here because function scope already exists:

var foo; // not a probem; it pollutes module namespace but doesn't leak anywhere
module.exports = function() {
  var foo; // can have another foo here, but it could be defined inside async
  return (async () => {/*...*/})()
}

Snippet 1 and 2 behave differently because of the differences between regular and arrow functions. A function in snippet 1 can be bound, use arguments, etc, while a function in snippet 2 cannot.

Snippet 2 is generally a preferable way.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

This is by no means a complete answer as a complete answer would require far too much detail. This should be a comment, but it's still too long to be so. Hopefully this will be enough to give you a start on doing the research yourself.

The most important thing to note is that module.exports and functions are two concepts in javascript that aren't tied directly to each other.

module.exports is a way of declaring that something in the file is accessible when imported into another file. It doesn't have to be a function.

module.exports = ""; //exports a string
module.exports = {name:"john"}; //exports an object
module.exports = 3.14159; //exports a number

functions are some of the many "things" in javascript. Broadly, their purpose it to take something and do something with it. There are primarily two forms:

function(){ } 

and

()=>{}

You can learn more about the difference between the two forms here: http://2ality.com/2012/04/arrow-functions.html

There are also asynchronous functions which are functions that are preceded with the keyword "async" and allow processing to happen in the background. You can learn more about asynchronous functions here: http://2ality.com/2016/02/async-functions.html.

I'm not affiliated with 2ality.com, but it is a really good resource.

Good luck!

John Henry
  • 2,419
  • 2
  • 20
  • 22