mirror of
https://github.com/puppeteer/puppeteer
synced 2024-06-14 14:02:48 +00:00
89 lines
2.0 KiB
TypeScript
89 lines
2.0 KiB
TypeScript
|
import {TimeoutError} from '../common/Errors.js';
|
||
|
|
||
|
/**
|
||
|
* @internal
|
||
|
*/
|
||
|
|
||
|
export interface DeferredPromise<T> extends Promise<T> {
|
||
|
finished: () => boolean;
|
||
|
resolved: () => boolean;
|
||
|
resolve: (_: T) => void;
|
||
|
reject: (_: Error) => void;
|
||
|
}
|
||
|
/**
|
||
|
* Creates an returns a promise along with the resolve/reject functions.
|
||
|
*
|
||
|
* If the promise has not been resolved/rejected withing the `timeout` period,
|
||
|
* the promise gets rejected with a timeout error.
|
||
|
*
|
||
|
* @internal
|
||
|
*/
|
||
|
|
||
|
export function createDeferredPromiseWithTimer<T>(
|
||
|
timeoutMessage: string,
|
||
|
timeout = 5000
|
||
|
): DeferredPromise<T> {
|
||
|
let isResolved = false;
|
||
|
let isRejected = false;
|
||
|
let resolver = (_: T): void => {};
|
||
|
let rejector = (_: Error) => {};
|
||
|
const taskPromise = new Promise<T>((resolve, reject) => {
|
||
|
resolver = resolve;
|
||
|
rejector = reject;
|
||
|
});
|
||
|
const timeoutId = setTimeout(() => {
|
||
|
isRejected = true;
|
||
|
rejector(new TimeoutError(timeoutMessage));
|
||
|
}, timeout);
|
||
|
return Object.assign(taskPromise, {
|
||
|
resolved: () => {
|
||
|
return isResolved;
|
||
|
},
|
||
|
finished: () => {
|
||
|
return isResolved || isRejected;
|
||
|
},
|
||
|
resolve: (value: T) => {
|
||
|
clearTimeout(timeoutId);
|
||
|
isResolved = true;
|
||
|
resolver(value);
|
||
|
},
|
||
|
reject: (err: Error) => {
|
||
|
clearTimeout(timeoutId);
|
||
|
isRejected = true;
|
||
|
rejector(err);
|
||
|
},
|
||
|
});
|
||
|
}
|
||
|
/**
|
||
|
* Creates an returns a promise along with the resolve/reject functions.
|
||
|
*
|
||
|
* @internal
|
||
|
*/
|
||
|
|
||
|
export function createDeferredPromise<T>(): DeferredPromise<T> {
|
||
|
let isResolved = false;
|
||
|
let isRejected = false;
|
||
|
let resolver = (_: T): void => {};
|
||
|
let rejector = (_: Error) => {};
|
||
|
const taskPromise = new Promise<T>((resolve, reject) => {
|
||
|
resolver = resolve;
|
||
|
rejector = reject;
|
||
|
});
|
||
|
return Object.assign(taskPromise, {
|
||
|
resolved: () => {
|
||
|
return isResolved;
|
||
|
},
|
||
|
finished: () => {
|
||
|
return isResolved || isRejected;
|
||
|
},
|
||
|
resolve: (value: T) => {
|
||
|
isResolved = true;
|
||
|
resolver(value);
|
||
|
},
|
||
|
reject: (err: Error) => {
|
||
|
isRejected = true;
|
||
|
rejector(err);
|
||
|
},
|
||
|
});
|
||
|
}
|