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 trialkaran Badhwar
Web Development Techdegree Graduate 18,135 Pointsaccessing res inside Callback
Hi, I am wondering how are we able to use res.render inside a callback
function getUsers(cb){
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) return cb(err);
const users = JSON.parse(data);
return cb(null, users);
});
}
app.get('/', (req,res) => {
getUsers((err,users) =>{
if(err){
res.render('error', {error:err})
} else{
res.render('index', {title: "users", users: users.users});
}
})
});
Because when we pass the callback, Callstack gets loaded up with getUsers(cb) Function, and we are no longer inside the route,then how the callback is using the res.render Method? And how do i know which values, methods are accessible to callbacks when being passed?
1 Answer
Steven Parker
231,269 PointsSince res
is one of the arguments passed to the callback ( " (req,res) => ... " ), then the code inside the callback has access to res
and all of its methods and values.
I apologize if you only wanted an answer from Caleb. I'll assume that's your intention if you tag someone specific within 24 hours of a posting in future.
karan Badhwar
Web Development Techdegree Graduate 18,135 PointsHey Steven Parker, thankyou sir for the response, no actually a lot of my questions are left unanswered and the specific ones which I feel the topic is important, I only tag in those one's as so that I can get at least an answer for those, as I search a lot and was stuck for a very long time, and sometimes if I need to complete the task to move forward that's why I post and tag and plus leave a message in the Slack, coz once I get stuck I cannot move forward until I understand sometimes that takes around 3-4 days of mine as well. I apologize if you felt that way sir.
And sir how would you able to answer my this question ? here
karan Badhwar
Web Development Techdegree Graduate 18,135 PointsI did select it as Best Answer and Sorry I guess I mistyped I meant would you be able to assist me in my other question sir please this one here
Caleb Kemp
12,755 PointsGlad to see your questions got answered
karan Badhwar
Web Development Techdegree Graduate 18,135 Pointskaran Badhwar
Web Development Techdegree Graduate 18,135 PointsHello sir Caleb Kemp , sorry for disturbing again, If you are online, would you be able to help me with this