Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Asynchronous Code in Express Asynchronous Code in Express Reduce Error Handling Code When Using Async/Await

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Having trouble understanding

Re-watched multiple times, Slowed down the speed, but I am not able to understandanything what happened and how it is happening, Could anyone please help me understand this

function asyncHandler(cb){
  return async (req,res,next)=> {
    try {
      await cb(req,res,next);
    } catch(err){
      res.render('error', {error:err});
    }
  }
}

function getUsers(){
  return new Promise((resolve, reject)=> {
    fs.readFile('data.json', 'utf-8', (err, data)=> {
      if(err){
        reject(err);
      } else {
        const users = JSON.parse(data);
        resolve(users);
      }
    });
  });
}

app.get('/', asyncHandler(async (req,res) => {
  const users = await getUsers();
  res.render('index', {title: "Users", users: users.users});
})); 

How are we over here able to access the req,res,next parameters where as it was not even declared inside the route? and how the flow is going of the program?

One last thing, when we called the asyncHandler, it returns a function, but how that anonymous function gets called, once we go to the '/' route the function gets called and it returns an anonymous function

1 Answer

Steven Parker
Steven Parker
229,783 Points

This situation is similar to the question you asked Friday in that req, res, and next are all parameters of the function that asyncHandler returns. We only see the declaration of them as parameters, the declaration of the arguments that will get passed is inside app.get.

Note that asyncHander is not passed to app.get, it is invoked immediately. So it is the function that asyncHandler returns that is passed to app.get, and it gets called from inside app.get.

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Hey Steven Parker, so basically you are saying as the asyncHandler function gets the the req, res and from the callback and it returns a middleware right, basically it is indirectly receiving the middleware?

but once after visiting the Route (/ ) the app.get already had called the asynchHandler, but it then returns an Anonymous Function, but doesn't that mean that route is completed already, then how on being returned with a function the route runs twice?

Steven Parker
Steven Parker
229,783 Points

The asyncHander runs while you are creating the route, and the function it returns becomes the callback (the actual handler). That handler then runs once when you access the route.

Armend Azemi
Armend Azemi
27,921 Points

But why do we pass req, res into the anonymous function when calling asyncHandler()? We are already re-calling the callback inside asyncHandler with req, res, next, so why are we doing it twice?