@httptoolkit/util
Version:
A tiny utility package, sharing JS code widely used across HTTP Toolkit projects
46 lines • 1.55 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.combineParallelCalls = exports.getDeferred = exports.doWhile = exports.delay = void 0;
const delay = (ms, options = {}) => new Promise((resolve) => {
const timer = setTimeout(resolve, ms);
if (options.unref && timer.unref) {
timer.unref();
}
});
exports.delay = delay;
async function doWhile(doFn, whileFn) {
do {
await doFn();
} while (await whileFn());
}
exports.doWhile = doWhile;
function getDeferred() {
let resolve;
let reject;
const promise = new Promise((resolveCb, rejectCb) => {
resolve = resolveCb;
reject = rejectCb;
});
return Object.assign(promise, { resolve, reject, promise });
}
exports.getDeferred = getDeferred;
/**
* Wrap a function, so that any parallel calls which happen while the async function
* is pending return the same value as the first call (so the function is only run
* once, but the result is shared). This is useful for expensive async functions or
* race conditions. This ignores arguments completely, and is only applicable for
* functions that don't need any other input.
*/
function combineParallelCalls(fn) {
let pendingPromise;
return () => {
if (pendingPromise === undefined) {
pendingPromise = fn().finally(() => {
pendingPromise = undefined;
});
}
return pendingPromise;
};
}
exports.combineParallelCalls = combineParallelCalls;
//# sourceMappingURL=promises.js.map
;