From 3afe3571af3c59c6e9cdba8fa13c3fafa0028456 Mon Sep 17 00:00:00 2001 From: Gyubong Date: Mon, 10 Oct 2022 21:02:06 +0900 Subject: [PATCH] Fix #2160 --- source/core/index.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/source/core/index.ts b/source/core/index.ts index 0a054fd64..eec536352 100644 --- a/source/core/index.ts +++ b/source/core/index.ts @@ -251,9 +251,8 @@ export default class Request extends Duplex implements RequestEvents { this.destroy(new AbortError(this)); } - this.options.signal?.addEventListener('abort', () => { - this.destroy(new AbortError(this)); - }); + this.abortHandler = this.abortHandler.bind(this); + this.options.signal?.addEventListener('abort', this.abortHandler, {once: true}); // Important! If you replace `body` in a handler with another stream, make sure it's readable first. // The below is run only once. @@ -545,6 +544,10 @@ export default class Request extends Duplex implements RequestEvents { return this; } + private abortHandler(): void { + this.destroy(new AbortError(this)); + } + private async _finalizeBody(): Promise { const {options} = this; const {headers} = options; @@ -664,6 +667,7 @@ export default class Request extends Duplex implements RequestEvents { response.once('end', () => { this._responseSize = this._downloadedSize; this.emit('downloadProgress', this.downloadProgress); + this.removeListener('abort', this.abortHandler); }); response.once('error', (error: Error) => { @@ -674,6 +678,7 @@ export default class Request extends Duplex implements RequestEvents { response.destroy(); this._beforeError(new ReadError(error, this)); + this.removeListener('abort', this.abortHandler); }); response.once('aborted', () => { @@ -684,6 +689,7 @@ export default class Request extends Duplex implements RequestEvents { message: 'The server aborted pending request', code: 'ECONNRESET', }, this)); + this.removeListener('abort', this.abortHandler); }); this.emit('downloadProgress', this.downloadProgress);