Skip to content

Commit ffd5762

Browse files
committed
Add support for using promises in Cursor.read()
1 parent 8f0db30 commit ffd5762

File tree

1 file changed

+45
-14
lines changed

1 file changed

+45
-14
lines changed

packages/pg-cursor/index.js

+45-14
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const util = require('util')
66

77
let nextUniqueID = 1 // concept borrowed from org.postgresql.core.v3.QueryExecutorImpl
88

9+
<<<<<<< HEAD
910
function Cursor(text, values, config) {
1011
EventEmitter.call(this)
1112

@@ -30,6 +31,25 @@ Cursor.prototype._ifNoData = function () {
3031
this._shiftQueue()
3132
if (this.connection) {
3233
this.connection.removeListener('rowDescription', this._rowDescription)
34+
=======
35+
class Cursor extends EventEmitter {
36+
constructor(text, values, config) {
37+
super()
38+
39+
this._conf = config || {}
40+
this.text = text
41+
this.values = values ? values.map(prepare) : null
42+
this.connection = null
43+
this._queue = []
44+
this.state = 'initialized'
45+
this._result = new Result(this._conf.rowMode, this._conf.types)
46+
this._Promise = this._conf.Promise || global.Promise
47+
this._cb = null
48+
this._rows = null
49+
this._portal = null
50+
this._ifNoData = this._ifNoData.bind(this)
51+
this._rowDescription = this._rowDescription.bind(this)
52+
>>>>>>> e800f45 (Add support for using promises in Cursor.read())
3353
}
3454
}
3555

@@ -216,20 +236,31 @@ Cursor.prototype.close = function (cb) {
216236
}
217237
}
218238

219-
Cursor.prototype.read = function (rows, cb) {
220-
if (this.state === 'idle' || this.state === 'submitted') {
221-
return this._getRows(rows, cb)
222-
}
223-
if (this.state === 'busy' || this.state === 'initialized') {
224-
return this._queue.push([rows, cb])
225-
}
226-
if (this.state === 'error') {
227-
return setImmediate(() => cb(this._error))
228-
}
229-
if (this.state === 'done') {
230-
return setImmediate(() => cb(null, []))
231-
} else {
232-
throw new Error('Unknown state: ' + this.state)
239+
read(rows, cb) {
240+
var result
241+
242+
if (!cb) {
243+
result = new this._Promise((resolve, reject) => {
244+
cb = (err, rows) => (err ? reject(err) : resolve(rows))
245+
})
246+
}
247+
if (this.state === 'idle' || this.state === 'submitted') {
248+
this._getRows(rows, cb)
249+
}
250+
else if (this.state === 'busy' || this.state === 'initialized') {
251+
this._queue.push([rows, cb])
252+
}
253+
else if (this.state === 'error') {
254+
setImmediate(() => cb(this._error))
255+
}
256+
else if (this.state === 'done') {
257+
setImmediate(() => cb(null, []))
258+
} else {
259+
throw new Error('Unknown state: ' + this.state)
260+
}
261+
262+
// Return the promise (or undefined)
263+
return result
233264
}
234265
}
235266

0 commit comments

Comments
 (0)