Client asks for dynamic information that will be served into 2 tables or lists in the same webpage. Lets say for example, to compare between 2 objects or articles.
JADE TEMPLATE
extends layout.jade
block content1
div= foo_table
block content2
div= bar_table
DATABASE QUERY
var table1 = db.query('select * from table where ...')
.then(function (result){
console.log(result);
});
var table2 = db.query('select * from table where ...')
.then(function (result){
console.log(result);
});
//I DON'T WANT TO SEND TO CONSOLE, JUST GET THE DATA, BUT IT IS ASYNCHRONOUS
Using return instead of console.log does not return the set of data.
.then(function (result){
return(result);
});
No variable defined inside then() is persistent.
ROUTER CODE
If I use this method it works, but...:
router.get('/', function(req, res, next) {
db.query('select * from table where ...')
.then(function (result){
res.send(result);
});
The problem is that it only can serve 1 query.
I want to serve 2 blocks simultaneously:
router.get('/', function(req, res, next) {
res.render('./index', { foo_table: table1, bar_table: table2});
};
The only think I get is the console.log but there's no way to pass the result of the query to the template (var tables do not store the result of the query).
Any variable that I create inside a "then" or async function is not persistent.
JSON.stringify or parse do not convert the result of these nested functions.
Calling back functions or creating functions after template variable definitions (footable: *, bartable: *) does not work.
As the queries are thenable I cannot find any way to convert into storable, or instead, collect results from various thenable queries to serve the final info and render the template variables.
Do I have to create a separate AJAX method for each table when the page is loaded?
I want to serve the whole page with the get method from begining.
If you are using (or the libraries you use are based on) something like Bluebird (or any other promise library) then you should be able to do it like this:
Promise.all([
db.query('select * from foo where ...'),
db.query('select * from bar where ...')
])
.spread(function(foo, bar) {
/* prepare data as you need them */
res.render('./index', { foo_table: foo, bar_table: bar});
});
Promise.all
asynchronously "waits" until both methods (the db queries) in the passed array have finished and returned, and then passes both results together to the callback passed to .spread()
(like in this example).