create-run-task

1.0.1 • Public • 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 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 ]))

Readme

Keywords

none

Package Sidebar

Install

npm i create-run-task

Weekly Downloads

4

Version

1.0.1

License

MIT

Unpacked Size

5.82 kB

Total Files

4

Last publish

Collaborators

  • m64253