Skip to content

Commit

Permalink
Merge branch 'main' into edge-118
Browse files Browse the repository at this point in the history
  • Loading branch information
soulgalore authored Oct 23, 2023
2 parents d08db80 + 2daaf5d commit 753cc73
Showing 1 changed file with 32 additions and 17 deletions.
49 changes: 32 additions & 17 deletions lib/core/seleniumRunner.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,40 @@ const defaults = {
const delay = ms => new Promise(res => setTimeout(res, ms));

/**
* Timeout a promise after ms. Use promise.race to compete
* about the timeout and the promise.
* @param {promise} promise - The promise to wait for
* @param {int} ms - how long in ms to wait for the promise to fininsh
* @param {string} errorMessage - the error message in the Error if we timeouts
* @function timeout
* @description Wraps a promise with a timeout, rejecting the promise with a TimeoutError if it does not settle within the specified time.
*
* @param {Promise} promise - The promise to wrap with a timeout.
* @param {number} ms - The number of milliseconds to wait before timing out.
* @param {string} errorMessage - The error message for the TimeoutError.
*
* @returns {Promise} - A promise that resolves with the value of the input promise if it settles within time, or rejects with a TimeoutError otherwise.
*/
async function timeout(promise, ms, errorMessage) {
let timer;

return Promise.race([
new Promise((resolve, reject) => {
timer = setTimeout(reject, ms, new TimeoutError(errorMessage));
return timer;
}),
promise.then(value => {
clearTimeout(timer);
return value;
})
]);
let timerId;
let finished = false;

// Create a new promise that rejects after `ms` milliseconds.
const timer = new Promise((_, reject) => {
timerId = setTimeout(() => {
if (!finished) {
// Reject with a TimeoutError if the input promise has not yet settled.
reject(new Error(errorMessage));
}
}, ms);
});

try {
// Race the input promise against the timer.
const result = await Promise.race([promise, timer]);
finished = true;
clearTimeout(timerId);
return result;
} catch (error) {
finished = true;
clearTimeout(timerId);
throw error;
}
}

/**
Expand Down

0 comments on commit 753cc73

Please sign in to comment.