From b73fe67aaa7d5d5b1a283b653e7cd7fb30a4cc21 Mon Sep 17 00:00:00 2001 From: amihhs <59364234+amihhs@users.noreply.github.com> Date: Fri, 29 Jul 2022 18:06:59 +0800 Subject: [PATCH] fix: do not retry when fetch is aborted (#112) --- src/fetch.ts | 6 +++++- test/index.test.ts | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/fetch.ts b/src/fetch.ts index 281cbbb..143621a 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -60,8 +60,12 @@ export function createFetch (globalOptions: CreateFetchOptions): $Fetch { const { fetch, Headers } = globalOptions function onError (ctx: FetchContext): Promise> { + // Is Abort + // If it is an active abort, it will not retry automatically. + // https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names + const isAbort = (ctx.error && ctx.error.name === 'AbortError') || false // Retry - if (ctx.options.retry !== false) { + if (ctx.options.retry !== false && !isAbort) { const retries = typeof ctx.options.retry === 'number' ? ctx.options.retry : (isPayloadMethod(ctx.options.method) ? 0 : 1) diff --git a/test/index.test.ts b/test/index.test.ts index d5c5fbb..9656726 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -105,4 +105,14 @@ describe('ohmyfetch', () => { const err = await $fetch('', { baseURL: getURL('404'), retry: 3 }).catch(err => err) expect(err.request).to.equal(getURL('404')) }) + + it('abort with retry', () => { + const controller = new AbortController() + async function abortHandle () { + controller.abort() + const res = await $fetch('', { baseURL: getURL('ok'), retry: 3, signal: controller.signal }) + console.log('res', res) + } + expect(abortHandle()).rejects.toThrow(/aborted/) + }) })