From 66a94347bb771798c125276702fa2a479ab77c0a Mon Sep 17 00:00:00 2001 From: Bluenix Date: Fri, 28 May 2021 17:39:32 +0200 Subject: [PATCH] Add support for using promises in Cursor.read() --- packages/pg-cursor/index.js | 39 +++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/packages/pg-cursor/index.js b/packages/pg-cursor/index.js index 8e8552be8..ec6d759a7 100644 --- a/packages/pg-cursor/index.js +++ b/packages/pg-cursor/index.js @@ -17,6 +17,7 @@ class Cursor extends EventEmitter { this._queue = [] this.state = 'initialized' this._result = new Result(this._conf.rowMode, this._conf.types) + this._Promise = this._conf.Promise || global.Promise this._cb = null this._rows = null this._portal = null @@ -198,6 +199,14 @@ class Cursor extends EventEmitter { } close(cb) { + var promise + + if (!cb) { + promise = new this._Promise((resolve, reject) => { + cb = (err) => (err ? reject(err) : resolve()) + }) + } + if (!this.connection || this.state === 'done') { if (cb) { return setImmediate(cb) @@ -213,23 +222,33 @@ class Cursor extends EventEmitter { cb() }) } + + return promise } read(rows, cb) { - if (this.state === 'idle' || this.state === 'submitted') { - return this._getRows(rows, cb) - } - if (this.state === 'busy' || this.state === 'initialized') { - return this._queue.push([rows, cb]) - } - if (this.state === 'error') { - return setImmediate(() => cb(this._error)) + var result + + if (!cb) { + result = new this._Promise((resolve, reject) => { + cb = (err, rows) => (err ? reject(err) : resolve(rows)) + }) } - if (this.state === 'done') { - return setImmediate(() => cb(null, [])) + + if (this.state === 'idle' || this.state === 'submitted') { + this._getRows(rows, cb) + } else if (this.state === 'busy' || this.state === 'initialized') { + this._queue.push([rows, cb]) + } else if (this.state === 'error') { + setImmediate(() => cb(this._error)) + } else if (this.state === 'done') { + setImmediate(() => cb(null, [])) } else { throw new Error('Unknown state: ' + this.state) } + + // Return the promise (or undefined) + return result } }