@@ -17,6 +17,7 @@ class Cursor extends EventEmitter {
17
17
this . _queue = [ ]
18
18
this . state = 'initialized'
19
19
this . _result = new Result ( this . _conf . rowMode , this . _conf . types )
20
+ this . _Promise = this . _conf . Promise || global . Promise
20
21
this . _cb = null
21
22
this . _rows = null
22
23
this . _portal = null
@@ -198,38 +199,52 @@ class Cursor extends EventEmitter {
198
199
}
199
200
200
201
close ( cb ) {
202
+ let promise
203
+
204
+ if ( ! cb ) {
205
+ promise = new this . _Promise ( ( resolve , reject ) => {
206
+ cb = ( err ) => ( err ? reject ( err ) : resolve ( ) )
207
+ } )
208
+ }
209
+
201
210
if ( ! this . connection || this . state === 'done' ) {
202
- if ( cb ) {
203
- return setImmediate ( cb )
204
- } else {
205
- return
206
- }
211
+ setImmediate ( cb )
212
+ return promise
207
213
}
208
214
209
215
this . _closePortal ( )
210
216
this . state = 'done'
211
- if ( cb ) {
212
- this . connection . once ( 'readyForQuery' , function ( ) {
213
- cb ( )
214
- } )
215
- }
217
+ this . connection . once ( 'readyForQuery' , function ( ) {
218
+ cb ( )
219
+ } )
220
+
221
+ // Return the promise (or undefined)
222
+ return promise
216
223
}
217
224
218
225
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 ) )
226
+ let promise
227
+
228
+ if ( ! cb ) {
229
+ promise = new this . _Promise ( ( resolve , reject ) => {
230
+ cb = ( err , rows ) => ( err ? reject ( err ) : resolve ( rows ) )
231
+ } )
227
232
}
228
- if ( this . state === 'done' ) {
229
- return setImmediate ( ( ) => cb ( null , [ ] ) )
233
+
234
+ if ( this . state === 'idle' || this . state === 'submitted' ) {
235
+ this . _getRows ( rows , cb )
236
+ } else if ( this . state === 'busy' || this . state === 'initialized' ) {
237
+ this . _queue . push ( [ rows , cb ] )
238
+ } else if ( this . state === 'error' ) {
239
+ setImmediate ( ( ) => cb ( this . _error ) )
240
+ } else if ( this . state === 'done' ) {
241
+ setImmediate ( ( ) => cb ( null , [ ] ) )
230
242
} else {
231
243
throw new Error ( 'Unknown state: ' + this . state )
232
244
}
245
+
246
+ // Return the promise (or undefined)
247
+ return promise
233
248
}
234
249
}
235
250
0 commit comments