create-run-task
v1.0.1
Published
Runs a "task" function but only executes it once while it's running. This can be useful when on the server side requesting the same external api endpoint from multiple pseudo-simultaneous incoming requests. This will ensure that you only make the request
Downloads
1
Readme
Runs a "task" function but only executes it once while it's running. This can be useful when on the server side requesting the same external api endpoint from multiple pseudo-simultaneous incoming requests. This will ensure that you only make the request to the external api endpoint once for all incoming request util it's complete.
/**
* @name createRunTask
* @function
* @param {Object} [options]
* @param {Number} [options.defaultTimeout] Defaults to 10000
* @returns {runTask}
*/
/**
* @name runTask
* @function
* @param {String} name
* @param {Function} task
* @param {Object} [options]
* @param {Number} [options.timeout] Defaults to defaultTimeout
* @returns {Promise}
*/
let counter = 0;
const runTask = createRunTask();
const name = 'foobar';
const task = () => new Promise((resolve) => {
counter += 1;
setTimeout(() => resolve(counter), 100);
});
Promise.all([
runTask(name, task),
runTask(name, task),
runTask(name, task),
runTask(name, task),
runTask(name, task)
])
.then(result => assert.deepEqual(result, [ 1, 1, 1, 1, 1 ]))