Ramda Adjunct 4.0.0

delayP.js

  1. import { curry, propOr, partial, nth } from 'ramda';
  2. import isNonNegative from './isNonNegative';
  3. import isInteger from './isInteger';
  4. /**
  5. * Creates a promise which resolves/rejects after the specified milliseconds.
  6. *
  7. * @func delayP
  8. * @memberOf RA
  9. * @category Function
  10. * @sig Number -> Promise Undefined
  11. * @sig {timeout: Number, value: a} -> Promise a
  12. * @param {number|Object} milliseconds number of milliseconds or options object
  13. * @return {Promise} A Promise that is resolved/rejected with the given value (if provided) after the specified delay
  14. * @example
  15. *
  16. * RA.delayP(200); //=> Promise(undefined)
  17. * RA.delayP({ timeout: 1000, value: 'hello world' }); //=> Promise('hello world')
  18. * RA.delayP.reject(100); //=> Promise(undefined)
  19. * RA.delayP.reject({ timeout: 100, value: new Error('error') }); //=> Promise(Error('error'))
  20. */
  21. const makeDelay = curry((settleFnPicker, opts) => {
  22. let timeout;
  23. let value;
  24. if (isInteger(opts) && isNonNegative(opts)) {
  25. timeout = opts;
  26. } else {
  27. timeout = propOr(0, 'timeout', opts);
  28. value = propOr(value, 'value', opts);
  29. }
  30. return new Promise((...args) => {
  31. const settleFn = settleFnPicker(args);
  32. setTimeout(partial(settleFn, [value]), timeout);
  33. });
  34. });
  35. const delayP = makeDelay(nth(0));
  36. delayP.reject = makeDelay(nth(1));
  37. export default delayP;