I’m trying to render a page of ‘projects’ retrieved from a database. There are two types of projects concerning the user, the projects which they own, and the projects which they are a member of.
I’m using two asynchronous database queries, however they could finish at different times and I only want to render the page upon them both completing.
Question:
How can I delay the rendering until the database transactions are complete?
var username = req.session.username;
var memberProjects = [];
var ownerProjects = [];
var membersQuery = false;
var ownerQuery = false;
projects.find({"members.username" : username}).toArray(function(err, results)
{
for(var i = 0; i < results.length; i++)
{
var project = {
title : results[i].title,
id : results[i]._id
}
memberProjects[i] = project;
}
membersQuery = true;
});
projects.find({owner : req.session.username}).toArray(function(err, results)
{
for(var i = 0; i < results.length; i++)
{
var project = {
title : results[i].title,
id : results[i]._id
}
ownerProjects[i] = project;
}
ownerQuery = true;
});
if( membersQuery && ownerQuery )
{
res.render('project', {
ownerProjects : ownerProjects,
memberProjects : memberProjects
});
}
I’ve got a working answer, i’m not sure whether it’s correct or not. Please correct me if there is a better approach. I’m calling a function at the end of each database transaction: