Skip to content

Commit

Permalink
stream: avoid unecessary nextTick
Browse files Browse the repository at this point in the history
If we are not going to emit 'close' then there is no reason to
schedule it.

PR-URL: #29194
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Backport-PR-URL: #29691
  • Loading branch information
ronag committed Oct 9, 2019
1 parent 3d88b76 commit bd05183
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions lib/internal/streams/destroy.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,25 @@ function destroy(err, cb) {
}

this._destroy(err || null, (err) => {
const emitClose = (this._writableState && this._writableState.emitClose) ||
(this._readableState && this._readableState.emitClose);
if (!cb && err) {
if (!this._writableState) {
process.nextTick(emitErrorAndCloseNT, this, err);
const emitNT = emitClose ? emitErrorAndCloseNT : emitErrorNT;
process.nextTick(emitNT, this, err);
} else if (!this._writableState.errorEmitted) {
this._writableState.errorEmitted = true;
process.nextTick(emitErrorAndCloseNT, this, err);
} else {
const emitNT = emitClose ? emitErrorAndCloseNT : emitErrorNT;
process.nextTick(emitNT, this, err);
} else if (emitClose) {
process.nextTick(emitCloseNT, this);
}
} else if (cb) {
process.nextTick(emitCloseNT, this);
if (emitClose) {
process.nextTick(emitCloseNT, this);
}
cb(err);
} else {
} else if (emitClose) {
process.nextTick(emitCloseNT, this);
}
});
Expand All @@ -56,18 +62,18 @@ function destroy(err, cb) {
}

function emitErrorAndCloseNT(self, err) {
emitErrorNT(self, err);
emitCloseNT(self);
self.emit('error', err);
self.emit('close');
}

function emitCloseNT(self) {
if (self._writableState && !self._writableState.emitClose)
return;
if (self._readableState && !self._readableState.emitClose)
return;
self.emit('close');
}

function emitErrorNT(self, err) {
self.emit('error', err);
}

function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
Expand All @@ -87,10 +93,6 @@ function undestroy() {
}
}

function emitErrorNT(self, err) {
self.emit('error', err);
}

function errorOrDestroy(stream, err) {
// We have tests that rely on errors being emitted
// in the same tick, so changing this is semver major.
Expand Down

0 comments on commit bd05183

Please sign in to comment.