Skip to content

Commit

Permalink
Add support for using promises in Cursor.read()
Browse files Browse the repository at this point in the history
  • Loading branch information
Bluenix2 committed Jun 22, 2021
1 parent 5a167b5 commit 73470a5
Showing 1 changed file with 29 additions and 10 deletions.
39 changes: 29 additions & 10 deletions packages/pg-cursor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
}
}

Expand Down

0 comments on commit 73470a5

Please sign in to comment.