@@ -150,11 +150,15 @@ ResultSet.prototype.resume = function resume() {
150150} ;
151151
152152ResultSet . prototype . close = function close ( cb ) {
153- this . finished = true ;
154- this . _running = false ;
153+ if ( this . closed ) {
154+ if ( typeof cb === 'function' ) {
155+ return cb ( ) ;
156+ }
157+ return ;
158+ }
155159 var self = this ;
156- process . nextTick ( function callEmitEndAndClose ( ) {
157- emitEnd . call ( self ) ;
160+ emitEnd . call ( self ) ;
161+ process . nextTick ( function callSendClose ( ) {
158162 sendClose . call ( self , cb ) ;
159163 } ) ;
160164} ;
@@ -297,16 +301,19 @@ function sendClose(cb) {
297301 if ( err ) {
298302 debug ( 'close failed: %s' , err ) ;
299303 } else {
300- self . closed = true ;
301304 emitClose . call ( self ) ;
302305 }
303306 if ( util . isFunction ( cb ) ) {
304307 cb ( err ) ;
305308 }
306309 }
307- this . _connection . closeResultSet ( {
308- resultSetId : this . id
309- } , done ) ;
310+ if ( this . _connection ) {
311+ this . _connection . closeResultSet ( {
312+ resultSetId : this . id
313+ } , done ) ;
314+ } else if ( util . isFunction ( cb ) ) {
315+ cb ( ) ;
316+ }
310317}
311318
312319function sendFetch ( ) {
@@ -348,17 +355,9 @@ function handleData(data) {
348355 this . emit ( 'data' , data . buffer ) ;
349356 }
350357
351- if ( isLast ( data ) ) {
352- this . finished = true ;
353- this . _running = false ;
354- this . closed = isClosed ( data ) ;
355- }
356-
357358 var self = this ;
358- if ( self . finished ) {
359- process . nextTick ( function callEmitEnd ( ) {
360- emitEnd . call ( self ) ;
361- } ) ;
359+ if ( isLast ( data ) ) {
360+ emitEnd . call ( self , isClosed ( data ) ) ;
362361 return ;
363362 }
364363
@@ -369,22 +368,35 @@ function handleData(data) {
369368 }
370369}
371370
372- function emitEnd ( ) {
371+ function emitEnd ( isClosed = false ) {
373372 /* jshint validthis:true */
374373 debug ( 'emit "end"' ) ;
375- this . emit ( 'end' ) ;
376- var self = this ;
377- if ( this . closed ) {
378- process . nextTick ( function callEmitClose ( ) {
379- emitClose . call ( self ) ;
380- } ) ;
374+ var shouldEmit = ! this . finished ;
375+ if ( ! this . finished ) {
376+ this . finished = true ;
377+ this . _running = false ;
381378 }
379+ let self = this ;
380+ process . nextTick ( function callEmitEnd ( ) {
381+ if ( shouldEmit ) {
382+ self . emit ( 'end' ) ;
383+ }
384+ if ( isClosed ) {
385+ emitClose . call ( self ) ;
386+ }
387+ } ) ;
382388}
383389
384390function emitClose ( ) {
385391 /* jshint validthis:true */
386392 debug ( 'emit "close"' ) ;
387- this . emit ( 'close' ) ;
393+ if ( ! this . closed ) {
394+ this . closed = true ;
395+ let self = this ;
396+ process . nextTick ( function callEmitClose ( ) {
397+ self . emit ( 'close' ) ;
398+ } ) ;
399+ }
388400}
389401
390402function isLast ( data ) {
0 commit comments