Express-async-handler npm package code question

Here is the meat of the javascript code

const asyncUtil = fn =>
function asyncUtilWrap(...args) {
  const fnReturn = fn(...args)
  const next = args[args.length-1]
  return Promise.resolve(fnReturn).catch(next)
   
}

I was just wondering why it structured the way it is structured. I get it accepts a function as an argument, I just don’t understand how the asyncUtilWrap function works. When does it get called ?

Here is a link to the github repo I am referring to. Brad Traversy (Udemy Instructor ) used it on one of his videos. I thought the code would be simple to understand. I was wrong.

Hey there,

Let us break it down:

  • asyncUtil is a function
    • It accepts one argument - supposedly a function
    • It returns a function - asyncUtilWrap
  • asyncUtilWrap is a function
    • It accepts any number of arguments
    • It returns a Promise

Let us see how we could use this:

const myCallbackFunc = (...args) => { // Do stuff and return };

const myWrapFunc = asyncUtil(myCallbackFunc);

const myPromise = myWrapFunc(arg1, arg2, ...argN);

// Or you could call it like this:
const myPromise = asyncUtil((...args) => { //Do stuff and return })(arg1, arg2, ...argN);

I hope that is clearer

So my question is (…args) equal to the function I am passing in. I can’t seem to make it appear in the console.

Here is what I have tried on codepen to see if I can make better sense of it.

const asyncUtil = fn => 
console.log(fn)
function lastName(...args){
  let name = fn(...args)
  console.log(name)
  console.log("Last name")
}

asyncUtil(function firstName(){return"Hello"})

In my example lastName never gets called so I never receive a console message. What logic am i missing?Thank you for taking the time. 

Here is the example of how it would be used in a project.

 express.get('/', asyncHandler(async (req, res, next) => {
 	const bar = await foo.findAll();
 	res.send(bar)
 }))

This is an error in the way the arrow function automagically returns. Also, there is no need to give lastName a name - it should be an anonymous function. This would be how you do it:

const asyncUtil = fn => {
  console.log(fn)
  return  function(...args){
    let name = fn(...args)
    console.log(name)
    console.log("Last name")
  }
}

// Now call it:
// There is no point in naming it,
//  because it will just be renamed to `fn`
asyncUtil(function (){return"Hello"})();
// Also, note we are not giving any ...args

Hope this helps