34 lines
871 B
JavaScript
34 lines
871 B
JavaScript
export function createSerializedRunner(task, options = {}) {
|
|
let activePromise = null;
|
|
|
|
return function runSerialized(...args) {
|
|
if (activePromise) {
|
|
return activePromise;
|
|
}
|
|
|
|
const timeoutMs = Number(options.timeoutMs);
|
|
let timeout;
|
|
const taskPromise = Promise.resolve(task(...args));
|
|
const nextPromise = Number.isFinite(timeoutMs) && timeoutMs > 0
|
|
? Promise.race([
|
|
taskPromise,
|
|
new Promise((_, reject) => {
|
|
timeout = setTimeout(() => {
|
|
reject(new Error(options.timeoutErrorMessage || "SERIALIZED_RUNNER_TIMEOUT"));
|
|
}, timeoutMs);
|
|
}),
|
|
])
|
|
: taskPromise;
|
|
|
|
activePromise = nextPromise
|
|
.finally(() => {
|
|
if (timeout) {
|
|
clearTimeout(timeout);
|
|
}
|
|
activePromise = null;
|
|
});
|
|
|
|
return activePromise;
|
|
};
|
|
}
|