0

I've trouble understanding the following javascript snippet. What I've learned so far is lambda functions have arguments (if any) & a body however the following method seems like it has an argument fn that lamda's into another set of arguments (req, res, next) & than it has a body that uses fn to call it.

This is super confusing for me. How exactly is this method working & how can it be written in simpler form?

const asyncMiddleware = fn =>
  (req, res, next) => {
    Promise.resolve(fn(req, res, next))
      .catch(next);
  };
user2498079
  • 2,580
  • 7
  • 28
  • 49
  • `asyncMiddleware` is a function that takes a function as argument and returns a function, which when called in turn takes three arguments and creates a promise with the functions first passed to `asyncMiddleware`. – deceze Nov 05 '19 at 12:59
  • if asyncMiddleware is taking function as an argument & it's executing the function stored in fn to return another function, how come the function returned by the function fn that's the argument of asyncMiddleware is being used again in the body (used by the promise). This is super confusing – user2498079 Nov 05 '19 at 13:02
  • 1
    1) It doesn't execute the function stored in fn to return another function. `asyncMiddleware` returns a new function (`(req, res, next) => { ... }`). The function `fn` is used later when this function (`(req, res, next) => { ... }`) is called. 2) What's confusing about it exactly? (I get that this can be slightly mindbending, but you have to be more precise about what exactly is bending your mind here.) – deceze Nov 05 '19 at 13:05

0 Answers0