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