I have a doubt related to async function on Express. I'm fetching some JSON from database and I'm getting the following error: Error: Can't set headers after they are sent.
I've read a little bit about it and it seems that it's related to the function having a Finished state or something like that.
I had the following code and it was crashing my application:
router.get('/home', isAuthenticated, function(req, res){
atendimentos.find({}, function(err, atendimentos) {
if(!err){
console.log(atendimentos);
return res.json(atendimentos);
}
})
res.render('home', {user: req.user});
})
But then I changed to this code:
router.get('/home', isAuthenticated, function(req, res){
//Added async to the function
atendimentos.find({}, async function(err, atendimentos) {
if(!err){
console.log(atendimentos);
return res.json(atendimentos);
}
})
res.render('home', {user: req.user});
})
The application stopped crashing but the error continues. I don't know why. Maybe I could get some help handling this?
Thanks
.then(function() { res.render('home', {user: req.user});(right after the parenthesis closing args of find method)?