Skip to content

Commit

Permalink
Merge pull request #279 from DoubleData/feature/respect-abort-signal
Browse files Browse the repository at this point in the history
Clear abort listener
  • Loading branch information
mindhells committed Jun 21, 2024
2 parents 028888c + 43530f4 commit e3fdb74
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 e3fdb74

Please sign in to comment.