47 lines
1.2 KiB
JavaScript
47 lines
1.2 KiB
JavaScript
//@ts-check
|
|
// Helpers for a tracked promise land
|
|
// by Humans for All
|
|
//
|
|
|
|
|
|
/**
|
|
* @typedef {(resolve: (value: any) => void, reject: (reason?: any) => void) => void} PromiseExecutor
|
|
*/
|
|
|
|
|
|
/**
|
|
* Eval which allows promises generated by the evald code to be tracked.
|
|
* @param {string} codeToEval
|
|
*/
|
|
export function evalWithPromiseTracking(codeToEval) {
|
|
const _Promise = globalThis.Promise;
|
|
/** @type {any[]} */
|
|
const trackedPromises = [];
|
|
|
|
const Promise = function ( /** @type {PromiseExecutor} */ executor) {
|
|
const promise = new _Promise(executor);
|
|
trackedPromises.push(promise);
|
|
|
|
promise.then = function (...args) {
|
|
const newPromise = _Promise.prototype.then.apply(this, args);
|
|
trackedPromises.push(newPromise);
|
|
return newPromise;
|
|
};
|
|
|
|
promise.catch = function (...args) {
|
|
const newPromise = _Promise.prototype.catch.apply(this, args);
|
|
trackedPromises.push(newPromise);
|
|
return newPromise;
|
|
};
|
|
|
|
return promise;
|
|
};
|
|
|
|
Promise.prototype = _Promise.prototype;
|
|
Object.assign(Promise, _Promise);
|
|
|
|
eval(codeToEval);
|
|
|
|
return _Promise.all(trackedPromises);
|
|
}
|