I have a database module which handles connection setup and pooling, and a query module that relies on the database module to execute queries. I'm adapting both of them to use Promises for asynchronous calls. So far, I've adapted the query module - now I wish to convert the database module.
Here's the problem: the database module should be usable both directly and implicitly by the query module (which currently relies on callbacks). How can I use promises in both modules' methods without turning this into a maze of twisty little passages?
Here's what I've done so far:
Database Module
getConnection: function(callback) { //this should return a promise
this.pool.getConnection(function(error, connection){
callback(error, connection);
});
},
Query Module this should then
on the getConnection
promise, execute query, and then reject/resolve for it's caller
request: function(queryRequest) {
return new Promise(function(resolve, reject){
Database.getConnection(function(error, connection){
if(error) {
reject({error: error, queryRequest: queryRequest});
} else {
connection.query(queryRequest.sql, queryRequest.values, function(error, rows, fields){
if(error) {
reject({error: error, queryRequest: queryRequest});
} else {
resolve({rows: rows, fields: fields, queryRequest: queryRequest});
}
connection.release()
});
}
});
});
},