Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clear abort listener #279

Merged
merged 1 commit into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions spec/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,34 @@ describe('axiosRetry(axios, { retries, retryCondition })', () => {
setTimeout(() => abortController.abort(), 50);
const timeStart = new Date().getTime();
});

it('should cancel old requests', (done) => {
const client = axios.create();
setupResponses(client, [
() => nock('http://example.com').get('/test').delay(100).reply(429),
() => nock('http://example.com').get('/test').delay(100).reply(429),
() => nock('http://example.com').get('/test').delay(100).reply(429)
]);
axiosRetry(client, {
retries: 2,
retryCondition: () => true,
retryDelay: () => 0
});
const abortController = new AbortController();
client
.get('http://example.com/test', { signal: abortController.signal })
.then(
() => done.fail(),
(error) => {
expect(error).toBeInstanceOf(CanceledError);
expect(new Date().getTime() - timeStart).toBeLessThan(300);
done();
}
)
.catch(done.fail);
setTimeout(() => abortController.abort(), 250);
const timeStart = new Date().getTime();
});
});
});

Expand Down
22 changes: 12 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,17 +255,19 @@ async function handleRetry(
if (config.signal?.aborted) {
return Promise.resolve(axiosInstance(config));
}
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => resolve(axiosInstance(config)), delay);
return new Promise((resolve) => {
const abortListener = () => {
clearTimeout(timeout);
resolve(axiosInstance(config));
};
const timeout = setTimeout(() => {
resolve(axiosInstance(config));
if (config.signal?.removeEventListener) {
config.signal.removeEventListener('abort', abortListener);
}
}, delay);
if (config.signal?.addEventListener) {
config.signal.addEventListener(
'abort',
() => {
clearTimeout(timeout);
resolve(axiosInstance(config));
},
{ once: true }
);
config.signal.addEventListener('abort', abortListener, { once: true });
}
});
}
Expand Down
Loading