1.6.1 • Published 12 months ago

timeable-promise v1.6.1

Weekly downloads
3,248
License
AGPL-3.0
Repository
github
Last release
12 months ago

Version Downloads Dependency Status Code Style Build Coverage Vulnerability License

Timeable Promise

Various asynchronous operations with timeout support.

Installation

$ yarn add timeable-promise
# or
$ npm install --save timeable-promise

API Reference

Various asynchronous operations with timeout support.

See: Promise
Example

const {
  chunk,
  concurrent,
  concurrents,
  consecutive,
  consecutives,
  parallel,
  poll,
  sequential,
  sleep,
  toNumber,
  untilSettledOrTimedOut,
  waitFor,
} = require('timeable-promise');

// ---------- chunk ----------
const chunked = chunk([1, 2, 3, 4], 2);
console.log('chunked: ', chunked);

// ---------- concurrent ----------
const concurrentSettled = await concurrent([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('concurrent settled: ', concurrentSettled);

// ---------- concurrents ----------
const concurrentsSettled = await concurrents([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('concurrents settled: ', concurrentsSettled);

// ---------- consecutive ----------
const consecutiveSettled = await consecutive([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('consecutive settled: ', consecutiveSettled);

// ---------- consecutives ----------
const consecutivesSettled = await consecutives([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('consecutives settled: ', consecutivesSettled);

// ---------- parallel ----------
const parallelSettled = await parallel([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('parallel settled: ', parallelSettled);

// ---------- poll ----------
const timer = poll((stopped) => {
  // Do something promising here...
  if (!stopped()) {
    // Do something when polling is not stopped...
  }
}, 100);
setTimeout(() => {
  // Simulate the end of polling.
  timer.stop();
}, 1000);

// ---------- sequential ----------
const sequentialSettled = await sequential([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('sequential settled: ', sequentialSettled);

// ---------- sleep ----------
console.time('sleep');
// Sleep for 1s.
await sleep(1000);
console.timeEnd('sleep');

// ---------- toNumber ----------
const converted = toNumber('1');
console.log('converted: ', 1);

// ---------- untilSettledOrTimedOut ----------
const response = await untilSettledOrTimedOut((resolve, reject, pending) => {
  // Promise executor with extra `pending` param to check if promise is not
  // timed-out yet.
  if (pending()) {
    resolve(true);
  }
}, (resolve, reject) => {
  // Timeout executor with option to either resolve or reject the promise.
  reject(Error('error'));
}, 5000)
  .catch(ex => console.log('nay :(', ex));
console.log(`resolved with ${response}, yay!`);

// ---------- waitFor ----------
// Long process running...
let inflight = true
const predicate = () => !inflight;
const timeout = 5000;
setTimeout(() => {
  // Long process done.
  inflight = false;
}, 1000);
console.time('waitFor');
await waitFor(predicate, timeout);
console.timeEnd('waitFor');

timeable-promise.chunk(array, size) ⇒ Array

Splits the array into groups of size. The final chunk would be the remaining elements.

Kind: static method of timeable-promise
Returns: Array - The chunked array.

ParamTypeDefaultDescription
arrayArrayThe original array.
sizenumber0The group size.

Example

const { chunk } = require('timeable-promise');
const chunked = chunk([1, 2, 3, 4], 2);
console.log('chunked: ', chunked);

timeable-promise.concurrent(array, executor, concurrency) ⇒ Promise.<Array.<module:timeable-promise.concurrent~settled>>

Run executor on all array items concurrently.

Kind: static method of timeable-promise
Returns: Promise.<Array.<module:timeable-promise.concurrent~settled>> - The concurrent outcome objects.

ParamTypeDefaultDescription
arrayArrayThe array items to be processed by executor.
executorexecutorExecutor function.
concurrencynumber0The max concurrent execution.

Example

const { concurrent } = require('timeable-promise');
const concurrentSettled = await concurrent([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('concurrent settled: ', concurrentSettled);

concurrent~executor : function

Executor function that will be executed concurrently.

Kind: inner typedef of concurrent

ParamTypeDescription
value*The current value being processed in the array.
indexnumberThe index of the current value being processed in the array.
arrayArrayThe array that is being processed concurrently.

Example

const executor = (value, index, array) => {
  // Do something promising here...
};

concurrent~settled : object

Concurrent outcome object.

Kind: inner typedef of concurrent
Properties

NameTypeDescription
reasonErrorThe exception object.
statusstringThe outcome status.
value*The outcome value.

timeable-promise.concurrents(array, executor, concurrency) ⇒ Promise.<Array.<module:timeable-promise.concurrent~settled>>

Run executor on all array groups concurrently.

Kind: static method of timeable-promise
Returns: Promise.<Array.<module:timeable-promise.concurrent~settled>> - The concurrent outcome objects.

ParamTypeDefaultDescription
arrayArrayThe array groups to be processed by executor.
executorexecutorExecutor function.
concurrencynumber0The max concurrent execution.

Example

const { concurrents } = require('timeable-promise');
const concurrentsSettled = await concurrents([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('concurrents settled: ', concurrentsSettled);

timeable-promise.consecutive(array, executor, concurrency) ⇒ Promise.<Array.<module:timeable-promise.consecutive~settled>>

Run executor on all array items consecutively.

Kind: static method of timeable-promise
Returns: Promise.<Array.<module:timeable-promise.consecutive~settled>> - The consecutive outcome objects.

ParamTypeDefaultDescription
arrayArrayThe array items to be processed by executor.
executorexecutorExecutor function.
concurrencynumber0The max consecutive execution.

Example

const { consecutive } = require('timeable-promise');
const consecutiveSettled = await consecutive([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('consecutive settled: ', consecutiveSettled);

consecutive~executor : function

Executor function that will be executed consecutively.

Kind: inner typedef of consecutive

ParamTypeDescription
value*The current value being processed in the array.
indexnumberThe index of the current value being processed in the array.
arrayArrayThe array that is being processed consecutively.
accumulatorArrayThe outcome array from previous call to this executor.

Example

const executor = (value, index, array, accumulator) => {
  // Do something promising here...
};

consecutive~settled : object

Consecutive outcome object.

Kind: inner typedef of consecutive
Properties

NameTypeDescription
reasonErrorThe exception object.
statusstringThe outcome status.
value*The outcome value.

timeable-promise.consecutives(array, executor, concurrency) ⇒ Promise.<Array.<module:timeable-promise.consecutive~settled>>

Run executor on all array groups consecutively.

Kind: static method of timeable-promise
Returns: Promise.<Array.<module:timeable-promise.consecutive~settled>> - The consecutive outcome objects.

ParamTypeDefaultDescription
arrayArrayThe array groups to be processed by executor.
executorexecutorExecutor function.
concurrencynumber0The max consecutive execution.

Example

const { consecutives } = require('timeable-promise');
const consecutivesSettled = await consecutives([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('consecutives settled: ', consecutivesSettled);

timeable-promise.parallel(array, executor, concurrency) ⇒ Promise.<Array.<module:timeable-promise.concurrent~settled>>

Provide parallel execution with concurrency support.

Kind: static method of timeable-promise
Returns: Promise.<Array.<module:timeable-promise.concurrent~settled>> - The parallel outcome objects.

ParamTypeDefaultDescription
arrayArrayThe array that is being processed in parallel.
executorexecutorExecutor function.
concurrencynumber0The max concurrent execution.

Example

const { parallel } = require('timeable-promise');
const parallelSettled = await parallel([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('parallel settled: ', parallelSettled);

timeable-promise.poll(executor, interval, immediately) ⇒ timer

Provide polling support without congestion when executor takes longer than interval.

Kind: static method of timeable-promise
Returns: timer - The return object with stop function.

ParamTypeDefaultDescription
executorexecutorExecutor function.
intervalnumber1000Delay interval.
immediatelybooleanfalseRun executor immediately in the beginning.

Example

const { poll } = require('timeable-promise');
const timer = poll((stopped) => {
  // Do something promising here...
  if (!stopped()) {
    // Do something when polling is not stopped...
  }
}, 100);
setTimeout(() => {
  // Simulate the end of polling.
  timer.stop();
}, 1000);

poll~executor : function

Executor function that is executed immediately by the Promise implementation.

Kind: inner typedef of poll

ParamTypeDescription
stoppedfunctionTrue if polling is stopped, otherwise false.

Example

const executor = (stopped) => {
  // Do something promising here...
  if (!stopped()) {
    // Do something when polling is not stopped...
  }
};

poll~timer : object

Timer object containing the polling stop function.

Kind: inner typedef of poll
Properties

NameTypeDescription
stopfunctionThe polling stop function.

timeable-promise.sequential(array, executor, concurrency) ⇒ Promise.<Array.<module:timeable-promise.consecutive~settled>>

Provide sequential execution with concurrency support.

Kind: static method of timeable-promise
Returns: Promise.<Array.<module:timeable-promise.consecutive~settled>> - The sequential outcome objects.

ParamTypeDefaultDescription
arrayArrayThe array that is being processed in sequential.
executorexecutorExecutor function.
concurrencynumber0The max consecutive execution.

Example

const { sequential } = require('timeable-promise');
const sequentialSettled = await sequential([...], (value, index, array) => {
  // Do something promising here...
  return value;
});
console.log('sequential settled: ', sequentialSettled);

timeable-promise.sleep(timeout) ⇒ Promise.<void>

Provide sleep support.

Kind: static method of timeable-promise

ParamTypeDescription
timeoutnumberTimeout.

Example

const { sleep } = require('timeable-promise');
console.time('sleep');
// Sleep for 1s.
await sleep(1000);
console.timeEnd('sleep');

timeable-promise.toNumber(value, defaultValue) ⇒ number

Converts value to number.

Kind: static method of timeable-promise
Returns: number - The converted number.

ParamTypeDefaultDescription
value*The value to be converted to number.
defaultValuenumber0The default number.

Example

const { toNumber } = require('timeable-promise');
const converted = toNumber('1');
console.log('converted: ', 1);

timeable-promise.untilSettledOrTimedOut(executor, timeoutExecutor, timeout) ⇒ Promise.<*>

Provide timeout support on Promise object.

Kind: static method of timeable-promise
Returns: Promise.<*> - Resolve or reject response value.

ParamTypeDescription
executorexecutorExecutor function.
timeoutExecutortimeoutExecutorTimeout executor function.
timeoutnumberTimeout.

Example

const { untilSettledOrTimedOut } = require('timeable-promise');
const executor = (resolve, reject, pending) => {
  // Do something promising here...
  if (pending()) {
    try {
      // Do something more promising here...
      resolve(true);
    } catch (ex) {
      reject(false);
    }
  }
};
const timeoutExecutor = (resolve, reject) => {
  try {
    resolve(true);
  } catch (ex) {
    reject(false);
  }
};
const timeout = 5000;
const response = await untilSettledOrTimedOut(executor, timeoutExecutor, timeout)
  .catch(ex => console.log('nay :(', ex));
console.log(`resolved with ${response}, yay!`);

untilSettledOrTimedOut~executor : function

Executor function that is executed immediately by the Promise implementation.

Kind: inner typedef of untilSettledOrTimedOut

ParamTypeDescription
resolvefunctionResolve the promise.
rejectfunctionReject the promise.
pendingfunctionTrue if Promise is not timed out, otherwise false.

Example

const executor = (resolve, reject, pending) => {
  // Do something promising here...
  if (pending()) {
    try {
      // Do something more promising here...
      resolve(true);
    } catch (ex) {
      reject(false);
    }
  }
};

untilSettledOrTimedOut~timeoutExecutor : function

Timeout executor function that is executed when timeout is reached.

Kind: inner typedef of untilSettledOrTimedOut

ParamTypeDescription
resolvefunctionResolve the promise.
rejectfunctionReject the promise.

Example

const timeoutExecutor = (resolve, reject) => {
  try {
    resolve(true);
  } catch (ex) {
    reject(false);
  }
};

timeable-promise.waitFor(predicate, timeout, interval) ⇒ Promise.<void>

Provide waiting support on given predicate.

Kind: static method of timeable-promise

ParamTypeDefaultDescription
predicatefunctionPredicate function.
timeoutnumberTimeout.
intervalnumber1000Check interval.

Example

const { waitFor } = require('timeable-promise');
// Long process running...
let inflight = true
const predicate = () => !inflight;
const timeout = 5000;
setTimeout(() => {
  // Long process done.
  inflight = false;
}, 1000);
console.time('waitFor');
await waitFor(predicate, timeout);
console.timeEnd('waitFor');

Development Dependencies

You will need to install Node.js as a local development dependency. The npm package manager comes bundled with all recent releases of Node.js. You can also use yarn as a package manager.

yarn or npm install will attempt to resolve any npm module dependencies that have been declared in the project’s package.json file, installing them into the node_modules folder.

$ yarn
# or
$ npm install

Run Benchmark, Leak, Lint, and Unit Tests

To make sure we did not break anything, let's run all the tests:

$ yarn test
# or
$ npm run test:lint; npm run test:unit; npm run test:bench; npm run test:leak

Run benchmark tests only:

$ yarn test:bench
# or
$ npm run test:bench

Run leak tests only:

$ yarn test:leak
# or
$ npm run test:leak

Run lint tests only:

$ yarn test:lint
# or
$ npm run test:lint

Run unit tests only:

$ yarn test:unit
# or
$ npm run test:unit

Contributing

If you would like to contribute code to Timeable Promise repository you can do so through GitHub by forking the repository and sending a pull request.

If you do not agree to Contribution Agreement, do not contribute any code to Timeable Promise repository.

When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also include appropriate test cases.

That's it! Thank you for your contribution!

License

Copyright (c) 2018 - 2023 Richard Huang.

This module is free software, licensed under: GNU Affero General Public License (AGPL-3.0).

Documentation and other similar content are provided under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

1.6.1

12 months ago

1.6.0

1 year ago

1.5.0

1 year ago

1.3.2

1 year ago

1.4.0

1 year ago

1.3.1

1 year ago

1.3.0

1 year ago

1.2.8

3 years ago

1.2.7

4 years ago

1.2.6

4 years ago

1.2.5

4 years ago

1.2.4

5 years ago

1.2.3

5 years ago

1.2.2

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.0

5 years ago