I recently started refactoring older callback-hell routes to use promises. (Note: the refactor is not complete so some of the following code is ugly)
Doing so broke my res.render()
function.
- I am using EJS for my render engine.
- Most of my promise chains are built off of MongoDB / Mongoose queries.
The basic app structure is a complex survey / quiz that sorts users into different categories. It stores their info and renders a custom EJS page at the end. Here's how the final call works, basically:
mongoose.model('Result')
.findOne({quizId: req.query.id})
.then(getPageData)
.then(renderPage)
.catch(errorHandler)
Simple enough, in theory.
Relevant functions:
let getPageData = (mongooseResult) => {
let resultsPage;
let analyticsData;
if (mongooseResult.answers.section1.question1.answer != null && mongooseResult.answers.section1.question1.answer != undefined){
let resultsPage = WP.getPage(wp_pages_data, 'slug', mongooseResult.coreFit);
let analyticsData = {
quizId: mongooseResult.quizId,
coreFit: mongooseResult.coreFit,
secondFit: mongooseResult.secondFit,
degree: mongooseResult.answers.section1.question1.answer,
year: mongooseResult.answers.section1.question2.answer,
concentration: mongooseResult.answers.section1.question3.answer,
views: mongooseResult.views,
}
mongooseResult.views++;
mongooseResult.save();
return [resultsPage, analyticsData, mongooseResult];
} else {
throw new Error('S1Q1 IS UNDEFINED');
}
};
let renderPage = ([resultsPage, analyticsData, mongooseResult]) => {
if (resultsPage != null && resultsPage != undefined){
// WHY IS MY RENDER NOT WORKING???
res.render('templates/' + mongooseResult.coreFit, Object.assign({}, WP.get_WP_data(resultsPage), getPartials(mongooseResult.modules), analyticsData), (err, html) => {if (err) console.log(err); else console.log(html);});
} else {
throw new Error('GETTING PAGE DATA RETURNED UNDEFINED');
}
};
What's funky is that the render()
actually fires; the callback ( (err, html) => {if (err) console.log(err); else console.log(html);}
) logs rendered HTML to my console, and no errors are fired.
Swapping the render for a simple res.send('wtf')
works - an actual response is sent to the client. (in this case the string 'wtf' ... )
The response just doesn't send back data. I don't get it. Any ideas?
via Zfalen
No comments:
Post a Comment