I am setting up a function in expresJS that using two simple functions execute two SQL queries using Knex to two different databases, but it must return as a response a promise.
function qDB1(status_id) {
return KnexDB1
.select()
.from('table1')
.where({
status: status_id
})
.orderBy('date')
.catch(function(err) {
console.log(err);
});
}
function qDB2 () {
var dateStart=Moment().format('L');
var dateEnd=Moment().add(1, 'days').format('L');
return KnexImc
.raw("EXEC SP_DB2 'QU', '"+dateStart+"','"+dateEnd+"'")
.catch(function(err) {
console.log(err);
});
}
QueryRepo.prototype.select = function(status_id) {
if ( !status_id) {
status_id=1;
}
var results = [];
qDB1(status_id)
.then(function (res) {
for(var idx = 0; idx < res.length; idx++){
console.log(res[idx]);
results.push(res[idx]);
}
});
qDB2()
.then(function (res) {
for(var idx2 = 0; idx2 < res.length; idx2++){
console.log(res[idx2]);
results.push(res[idx2]);
}
});
return Promise.all(results);
};
When I execute the functions qDB1
and qDB2
work well and load the data in results
, the problem is that when executing select
the promise arrives as an empty array.
I know I could return the resuls
array once the Knex promises are completed, but the answer needs to be a promise.