You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
851 B
JavaScript
34 lines
851 B
JavaScript
"use strict";
|
|
|
|
const capturePromise = require("capture-promise");
|
|
const debug = require("debug")("single-concurrent");
|
|
|
|
const { validateArguments } = require("@validatem/core");
|
|
const isFunction = require("@validatem/is-function");
|
|
const required = require("@validatem/required");
|
|
|
|
module.exports = function singleConcurrent(_func) {
|
|
let [ func ] = validateArguments(arguments, {
|
|
func: [ required, isFunction ]
|
|
});
|
|
|
|
let running = false;
|
|
|
|
return async function (... args) {
|
|
if (running === false) {
|
|
debug(`starting`);
|
|
running = true;
|
|
|
|
try {
|
|
return await capturePromise(() => func(... args));
|
|
} finally {
|
|
// Yes, this gets called *even if* the above successfully returns, before the resulting Promise is resolved.
|
|
debug(`completed`);
|
|
running = false;
|
|
}
|
|
} else {
|
|
debug(`already running; skipping`);
|
|
}
|
|
};
|
|
};
|