Skip to content

Commit

Permalink
Queue now gets flushed and every function call throws error, after a …
Browse files Browse the repository at this point in the history
…single error reaches its maximum retries.
  • Loading branch information
fyodordev committed May 1, 2019
1 parent ced6923 commit d2011f8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
15 changes: 13 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export default class CallHandler {
const wait = this.getBackoff(e, attemptNr);
if (wait) {
const result = timeout(wait, () => this.sendReq(request, attemptNr + 1));
this.blockRequests(result, this.rateLim)
if (attemptNr === 0) this.blockRequests(result, this.rateLim);
return await result;
} else {
// If getBackoff returns undefined that means no more retries should be made and error passed upward.
Expand All @@ -99,9 +99,20 @@ export default class CallHandler {
this.requestsLastPeriod = this.requestsLastPeriod + amount;
try {
await promise;
} finally {
this.requestsLastPeriod = this.requestsLastPeriod - amount;
return await this.checkQueue();
} catch (e) {
this.requestsLastPeriod = this.requestsLastPeriod - amount;
return await this.flushQueue(e);
}
}

// Remove all requests from the queue and reject their promises with the provided Error.
private flushQueue(reason: Error) {
while (this.queue.length > 0) {
// Pop requests off the queue and reject their promise
const re = this.queue.shift();
if (re && re.passPromise) { re.passPromise(new Promise((res, rej) => rej(reason))) };
}
}

Expand Down
10 changes: 8 additions & 2 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,12 @@ describe('RequestHandler', () => {
}
});

const func = async () => reqHandler.call(() => secondFetch());
let errcount = 0;
const func = async () => reqHandler.call(() => secondFetch())
.catch((e) => {
errcount += 1;
});

const looper = new Looper(func, 20);

let promise;
Expand All @@ -159,7 +164,8 @@ describe('RequestHandler', () => {
error = e;
}
const delta = Date.now() - timeA;

await new Promise((res) => setTimeout(() => res(), 1000));
expect(errcount).toBeGreaterThan(30);
expect(delta).toBeLessThan(800);
expect(delta).toBeGreaterThanOrEqual(700);
expect(error).toBeTruthy();
Expand Down

0 comments on commit d2011f8

Please sign in to comment.