From c4e41774b2281150df3817dd3bb0b191e45df33c Mon Sep 17 00:00:00 2001 From: Gyubong Lee Date: Tue, 3 May 2022 21:17:49 +0900 Subject: [PATCH] Add initial rejection when already aborted Same with : https://github.com/sindresorhus/got/pull/2020 --- index.js | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 17c579f..b3ec199 100644 --- a/index.js +++ b/index.js @@ -21,6 +21,14 @@ const getDOMException = errorMessage => globalThis.DOMException === undefined ? new AbortError(errorMessage) : new DOMException(errorMessage); +const getAbortedReason = signal => { + const reason = signal.reason === undefined ? + getDOMException('This operation was aborted.') : + signal.reason; + + return reason instanceof Error ? reason : getDOMException(reason); +}; + export default function pTimeout(promise, milliseconds, fallback, options) { let timer; @@ -39,15 +47,14 @@ export default function pTimeout(promise, milliseconds, fallback, options) { ...options }; - if (options && options.signal) { + if (options.signal) { const {signal} = options; + if (signal.aborted) { + reject(getAbortedReason(signal)); + } signal.addEventListener('abort', () => { - const reason = signal.reason === undefined ? - getDOMException('This operation was aborted.') : - signal.reason; - - reject(reason instanceof Error ? reason : getDOMException(reason)); + reject(getAbortedReason(signal)); }); }