Skip to content

Commit 73470a5

Browse files
committed
Add support for using promises in Cursor.read()
1 parent 5a167b5 commit 73470a5

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

packages/pg-cursor/index.js

+29-10
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class Cursor extends EventEmitter {
1717
this._queue = []
1818
this.state = 'initialized'
1919
this._result = new Result(this._conf.rowMode, this._conf.types)
20+
this._Promise = this._conf.Promise || global.Promise
2021
this._cb = null
2122
this._rows = null
2223
this._portal = null
@@ -198,6 +199,14 @@ class Cursor extends EventEmitter {
198199
}
199200

200201
close(cb) {
202+
var promise
203+
204+
if (!cb) {
205+
promise = new this._Promise((resolve, reject) => {
206+
cb = (err) => (err ? reject(err) : resolve())
207+
})
208+
}
209+
201210
if (!this.connection || this.state === 'done') {
202211
if (cb) {
203212
return setImmediate(cb)
@@ -213,23 +222,33 @@ class Cursor extends EventEmitter {
213222
cb()
214223
})
215224
}
225+
226+
return promise
216227
}
217228

218229
read(rows, cb) {
219-
if (this.state === 'idle' || this.state === 'submitted') {
220-
return this._getRows(rows, cb)
221-
}
222-
if (this.state === 'busy' || this.state === 'initialized') {
223-
return this._queue.push([rows, cb])
224-
}
225-
if (this.state === 'error') {
226-
return setImmediate(() => cb(this._error))
230+
var result
231+
232+
if (!cb) {
233+
result = new this._Promise((resolve, reject) => {
234+
cb = (err, rows) => (err ? reject(err) : resolve(rows))
235+
})
227236
}
228-
if (this.state === 'done') {
229-
return setImmediate(() => cb(null, []))
237+
238+
if (this.state === 'idle' || this.state === 'submitted') {
239+
this._getRows(rows, cb)
240+
} else if (this.state === 'busy' || this.state === 'initialized') {
241+
this._queue.push([rows, cb])
242+
} else if (this.state === 'error') {
243+
setImmediate(() => cb(this._error))
244+
} else if (this.state === 'done') {
245+
setImmediate(() => cb(null, []))
230246
} else {
231247
throw new Error('Unknown state: ' + this.state)
232248
}
249+
250+
// Return the promise (or undefined)
251+
return result
233252
}
234253
}
235254

0 commit comments

Comments
 (0)