From 6d98b0847cf39ff327ce45c663ee4230d7b9104a Mon Sep 17 00:00:00 2001 From: "Brian M. Carlson" Date: Fri, 9 Jun 2017 16:35:01 -0500 Subject: [PATCH] Actual promisification of client.query --- lib/client.js | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/lib/client.js b/lib/client.js index 9fb2f8b1..d489ff8d 100644 --- a/lib/client.js +++ b/lib/client.js @@ -349,19 +349,37 @@ Client.prototype.copyTo = function (text) { }; Client.prototype.query = function(config, values, callback) { - //can take in strings, config object or query object - var query = (typeof config.submit == 'function') ? config : - new Query(config, values, callback); + var promise; + var isQueryable = typeof config.submit == 'function'; + var query; + // if we receive an object with a 'submit' function we delegate + // processing to the passed object - this is how pg.Query, QueryStream, and Cursor work + if (isQueryable) { + query = config; + } else { + query = new Query(config, values, callback); + if (!query.callback) { + promise = new global.Promise(function (resolve, reject) { + query.on('error', reject); + query.on('end', resolve); + }); + } + } if(this.binary && !query.binary) { query.binary = true; } + + // TODO - this is a smell if(query._result) { query._result._getTypeParser = this._types.getTypeParser.bind(this._types); } this.queryQueue.push(query); this._pulseQueryQueue(); - return query; + + // if we were passed a queryable, return it + // otherwise return callback/promise result + return isQueryable ? query : promise; }; Client.prototype.end = function(cb) {