javascript - How can I properly promisify these two database methods for nodejs? -
i have database module handles connection setup , pooling, , query module relies on database module execute queries. i'm adapting both of them use promises asynchronous calls. far, i've adapted query module - wish convert database module.
here's problem: database module should usable both directly , implicitly query module (which relies on callbacks). how can use promises in both modules' methods without turning maze of twisty little passages?
here's i've done far:
database module
getconnection: function(callback) { //this should return promise this.pool.getconnection(function(error, connection){ callback(error, connection); }); },
query module should then
on getconnection
promise, execute query, , reject/resolve 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() }); } }); }); },
getconnection
should return promise [for connection]
rather not, should use disposer pattern instead, , call connection.release()
itself:
function withconnection(callback) { var pool = this.pool; var conn = new promise(function(resolve, reject) { pool.getconnection(function(error, connection){ if (error) reject(error); else resolve(connection); }); }); return conn.then(function(connection) { var res = conn.then(callback); // safe call return res.then(fin); // `finally` shim function fin() { connection.release(); return res; } }); } function request(queryrequest) { return database.withconnection(function(connection) { return new promise(function(resolve, reject) { connection.query(queryrequest.sql, queryrequest.values, function(error, rows, fields) { if (error) reject(error); else resolve({rows: rows, fields: fields, queryrequest: queryrequest}); }); }); }).catch(function(error) { error.queryrequest = queryrequest; throw error; }); }
Comments
Post a Comment