Reputation: 1776
I wrote the following module which connects to postgresql or SQLServer depending a the Type var value:
exports.GetQueryResult = function (type, Name,con,callback) {
var sql='';
if (Type ='PG') {
sql=sql + ' SELECT …………..';
pg.connect(con, function(err, client, done) {
if(err) {
console.log("Error :" + err);
return callback(err);
}
client.query(sql,[Name], function(err, Result) {
if(err) {
console.log("Error: " +err);
return callback(err);
}
return callback(null,Result);
done();
});
});
}
else
{
sql=sql + ' SELECT …..';
sql.open(con, function (err, conn,done) {
if (err) {
console.log("Error :" + err);
return callback(err);
}
conn.queryRaw(sql,Name, function (err, Result) {
if (err) {
console.log("Error ejecutando la consulta. Error: " +err);
return callback(err);
}
callback(null,Result);
done;
});
});
}
};
I call this function from:
var MultiBD = require('./MultiBD.js');
var LayerType=['PG','SQL','PG'];
var con=’’;
for (var i=1; i<=Layers.length; i++) {
if (Layers[i-1]!=undefined){
con=MultiBD.conexion(LayerType [i-1],server,BD);
MultiBD.GetQueryResult(LayerType[i-1], Name[i-1],con,
function (err,Result){
console.log('Result : ' + Result.rows.length);
}
);
}
}
The results are:
Result : 111
Result : 2888
Result : 5
I get three query results. The first one returns 111 rows, the second one 2888 and the third one 5.
What i need is to get only one unique result with all the 3004 rows (111+2888+5).
Regards,
Upvotes: 0
Views: 76
Reputation: 6017
You'll need some flow control to wait until all 3 methods have completed their DB calls before printing their results. There are packages for this, either of the callback variety or Promises.
Here is an example using the async package (which is of the callback variety of flow-control):
var async = require('async');
var totalResults = 0;
async.each( Layers, function eachMethod( layer, eachCb ){
var con = MultiBD.conexion(layer,server,BD);
MultiBD.GetQueryResult(LayerType[i-1], Name[i-1],con, function (err,Result) {
if( err ) return eachCb( err );
totalResults += Result.rows.length;
eachCb( null );
} );
}, function finalEach( eachErr ){
if( eachErr ) console.log( "There was an error. " + eachErr );
else console.log( "Result: " + totalResults );
});
In this call, a method (the eachMethod
) is called on every item in the array. The results are stored in a shared variable. When all items have completed, the finalEach
method is called. Here errors have bubbled up (which you can choose to check or not) and all calls have completed, so we can simply print the value of the shared variable.
Upvotes: 1