Skip to content

Commit

Permalink
Implement waitOnceForAllXhrFinished to remove listeners after all req…
Browse files Browse the repository at this point in the history
…uests are done
  • Loading branch information
mendelgusmao committed Apr 26, 2020
1 parent 8984221 commit 2e363fa
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,19 @@ export class PendingXHR {
finishedWithSuccessXhrs: Set<Request>;
finishedWithErrorsXhrs: Set<Request>;
promisees: Array<Promise<void>>
requestListener: (request: ResolvableRequest) => void;
requestFailedListener: (request: ResolvableRequest) => void;
requestFinishedListener: (request: ResolvableRequest) => void;

constructor(page: Page) {
this.promisees = [];
this.page = page;
this.resourceType = 'xhr';
// page.setRequestInterception(true);
this.pendingXhrs = new Set();
this.finishedWithSuccessXhrs = new Set();
this.finishedWithErrorsXhrs = new Set();
page.on('request', (request: ResolvableRequest) => {

this.requestListener = (request: ResolvableRequest) => {
if (request.resourceType() === this.resourceType) {
this.pendingXhrs.add(request);
this.promisees.push(
Expand All @@ -30,8 +33,9 @@ export class PendingXHR {
}),
);
}
});
page.on('requestfailed', (request: ResolvableRequest) => {
};

this.requestFailedListener = (request: ResolvableRequest) => {
if (request.resourceType() === this.resourceType) {
this.pendingXhrs.delete(request);
this.finishedWithErrorsXhrs.add(request);
Expand All @@ -40,8 +44,9 @@ export class PendingXHR {
delete request.resolver;
}
}
});
page.on('requestfinished', (request: ResolvableRequest) => {
};

this.requestFinishedListener = (request: ResolvableRequest) => {
if (request.resourceType() === this.resourceType) {
this.pendingXhrs.delete(request);
this.finishedWithSuccessXhrs.add(request);
Expand All @@ -50,7 +55,11 @@ export class PendingXHR {
delete request.resolver;
}
}
});
};

page.on('request', this.requestListener);
page.on('requestfailed', this.requestFailedListener);
page.on('requestfinished', this.requestFinishedListener);
}

async waitForAllXhrFinished() {
Expand All @@ -60,6 +69,14 @@ export class PendingXHR {
await Promise.all(this.promisees);
}

async waitOnceForAllXhrFinished() {
await this.waitForAllXhrFinished();

this.page.removeListener('request', this.requestListener);
this.page.removeListener('requestfailed', this.requestFailedListener);
this.page.removeListener('requestfinished', this.requestFinishedListener);
}

pendingXhrCount() {
return this.pendingXhrs.size;
}
Expand Down

0 comments on commit 2e363fa

Please sign in to comment.