Reputation: 328
I want to run two queries and when they finish pass the data to res.render
. I've read about promises but I still don't understand how to make the second query pass data and put it in render. Basically I'd like to run the queryTable
function/promise twice but the second time with thegraphquery
.
app.get('/clickus', function(req, res) {
var thequery = 'SELECT ab FROM table';
var thegraphquery = `select cd FROM table `;
let promise = queryTable(thequery);
promise.then(
data => res.render('clickus', {
'mydata': data
})
);
});
function queryTable(thequery) {
return new Promise(function(resolve, reject) {
var con = new msSqlConnecter.msSqlConnecter(config);
con.connect().then(function() {
new con.Request(thequery).onComplate(function(count, datas) {
resolve(datas);
}).onError(function(err) {
console.log(err);
}).Run();
}).catch(function(ex) {
console.log(ex);
});
});
}
Upvotes: 0
Views: 50
Reputation: 4010
const createPromise = (time) => new Promise((resolve, reject) => {
setTimeout(() => resolve(time), time);
});
Promise.all([createPromise(1000), createPromise(2000)])
.then((result) => console.log(result))
You could use Promise.all api Promise.all
Promise.all accepts an array of promises and the then only fires when all promises resolved. In the then of the Promise.all you accept an array of results for each promise.
app.get('/clickus', function(req, res) {
var thequery = 'SELECT ab FROM table';
var thegraphquery = `select cd FROM table `;
Promise.all([queryTable(thequery), queryTable(thegraphquery)])
.then(
data => res.render('clickus', {
'mydata': data // an array of data ['thequery result', 'thegraphquery result']
})
);
});
Upvotes: 2
Reputation: 15115
Use Promise.all
to execute both queries simultaneously and wait on both of their results before passing them to res.render
:
app.get('/clickus', function(req, res) {
var thequery = 'SELECT ab FROM table';
var thegraphquery = `select cd FROM table `;
Promise.all([queryTable(thequery), queryTable(thegraphquery)])
.then(results => {
res.render('clickus', {
'queryData': results[0],
'graphQueryData': results[1]
});
});
});
Upvotes: 1