Skip to content

Commit

Permalink
Clear abort listener
Browse files Browse the repository at this point in the history
Fixes #278
  • Loading branch information
michal-billtech committed Jun 21, 2024
1 parent ad9bffb commit 43530f4
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
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

0 comments on commit 43530f4

Please sign in to comment.