function waitForAjaxCalls(page: Page) { const task = new Task(); let _expectedCount = Infinity; let processedCalls = 0; const handler = (req: HTTPRequest) => { if (req.method() !== 'POST') { return; } if (req.response().ok()) { ++processedCalls; } else { task.reject(new InternalServerErrorException('Failed to load data')); } if (processedCalls >= _expectedCount) { task.resolve(); } }; page.on('requestfinished', handler); return (expectedCount: number, timeLimit: number) => { _expectedCount = expectedCount; if (processedCalls >= expectedCount) { task.resolve(); } const timeoutTask = new Task(); const timeoutId = setTimeout(() => { timeoutTask.reject(new InternalServerErrorException(`Timeout for data load`)); }, timeLimit); return Promise.race([task, timeoutTask]).finally(() => { clearTimeout(timeoutId); page.off('requestfinished', handler); }); }; } // Usage const callInterceptor = waitForAjaxCalls(page); const expectedAjaxCallCounts = 10; // image some async action await monthsAjaxCallInterceptor(expectedAjaxCallCounts, 10 * 1000); // 10 seconds timeout