@prismicio/client
Version:
The official JavaScript + TypeScript client library for Prismic
55 lines (53 loc) • 1.64 kB
JavaScript
//#region src/lib/pLimit.ts
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* Creates a limiting function that will only execute one promise at a time and
* respect a given interval between each call.
*
* @param args - Options for the function, `interval` is the minimum time to
* wait between each promise execution.
*
* @returns A limiting function as per configuration, see {@link LimitFunction}.
*/
const pLimit = ({ interval } = {}) => {
const queue = [];
let busy = false;
let lastCompletion = 0;
const resumeNext = () => {
if (!busy && queue.length > 0) {
var _queue$shift;
(_queue$shift = queue.shift()) === null || _queue$shift === void 0 || _queue$shift();
busy = true;
}
};
const next = () => {
busy = false;
resumeNext();
};
const run = async (function_, resolve, arguments_) => {
const timeSinceLastCompletion = Date.now() - lastCompletion;
if (interval && timeSinceLastCompletion < interval) await sleep(interval - timeSinceLastCompletion);
const result = (async () => function_(...arguments_))();
resolve(result);
try {
await result;
} catch {}
lastCompletion = Date.now();
next();
};
const enqueue = (function_, resolve, arguments_) => {
new Promise((internalResolve) => {
queue.push(internalResolve);
}).then(run.bind(void 0, function_, resolve, arguments_));
(async () => {
await Promise.resolve();
if (!busy) resumeNext();
})();
};
return ((function_, ...arguments_) => new Promise((resolve) => {
enqueue(function_, resolve, arguments_);
}));
};
//#endregion
exports.pLimit = pLimit;
//# sourceMappingURL=pLimit.cjs.map