Skip to content

Commit

Permalink
Cancel timer on rejection in wait.js
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenwdv committed Aug 25, 2022
1 parent be244b8 commit 3250877
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 14 deletions.
2 changes: 1 addition & 1 deletion crawler.js
Expand Up @@ -298,7 +298,7 @@ async function crawl(url, options) {
);
// Create a new incognito browser context.
const context = options.browserContext || await browser.createIncognitoBrowserContext();
if (!options.browserContext) {
if (browser) {
// Close non-incognito window
context.once(
'targetcreated',
Expand Down
7 changes: 4 additions & 3 deletions helpers/wait.d.ts
@@ -1,7 +1,8 @@
export = wait;
/**
* @param {Promise<any>} promise
* @template T
* @param {Promise<T>} promise
* @param {number} maxMs max running time, 0 to disable timeout
* @returns {Promise<any>}
* @returns {Promise<T>}
*/
declare function wait(promise: Promise<any>, maxMs: number): Promise<any>;
declare function wait<T>(promise: Promise<T>, maxMs: number): Promise<T>;
21 changes: 11 additions & 10 deletions helpers/wait.js
@@ -1,19 +1,20 @@
/**
* @param {Promise<any>} promise
* @template T
* @param {Promise<T>} promise
* @param {number} maxMs max running time, 0 to disable timeout
* @returns {Promise<any>}
* @returns {Promise<T>}
*/
function wait(promise, maxMs) {
if (!maxMs) {return promise;}
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('Operation timed out'));
}, maxMs);

promise.then(result => {
clearTimeout(timeout);
resolve(result);
}).catch(e => reject(e));
const timeout = setTimeout(
() => reject(new Error("Operation timed out")),
maxMs
);
promise
.finally(() => clearTimeout(timeout))
.then(resolve)
.catch(reject);
});
}

Expand Down

0 comments on commit 3250877

Please sign in to comment.