source: node_modules/ramda-adjunct/src/async.js@ d24f17c

main
Last change on this file since d24f17c was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 1.6 KB
Line 
1import { curryN, bind } from 'ramda';
2
3import resolveP from './resolveP';
4import rejectP from './rejectP';
5
6/**
7 * Takes a generator function and returns an async function.
8 * The async function returned is a curried function whose arity matches that of the generator function.
9 *
10 * Note: This function is handy for environments that does support generators but doesn't support async/await.
11 *
12 * @func async
13 * @memberOf RA
14 * @since {@link https://char0n.github.io/ramda-adjunct/2.16.0|v2.16.0}
15 * @category Function
16 * @sig Promise c => (a, b, ...) -> a -> b -> ... -> c
17 * @param {Function} generatorFn The generator function
18 * @return {Function} Curried async function
19 * @see {@link https://www.promisejs.org/generators/}
20 * @example
21 *
22 * const asyncFn = RA.async(function* generator(val1, val2) {
23 * const a = yield Promise.resolve(val1);
24 * const b = yield Promise.resolve(val2);
25 *
26 * return a + b;
27 * });
28 *
29 * asyncFn(1, 2); //=> Promise(3)
30 *
31 */
32const async = curryN(1, (generatorFn) => {
33 function asyncWrapper(...args) {
34 const iterator = bind(generatorFn, this)(...args);
35
36 const handle = (result) => {
37 const resolved = resolveP(result.value);
38
39 return result.done
40 ? resolved
41 : resolved.then(
42 (value) => handle(iterator.next(value)),
43 (error) => handle(iterator.throw(error))
44 );
45 };
46
47 try {
48 return handle(iterator.next());
49 } catch (error) {
50 return rejectP(error);
51 }
52 }
53
54 if (generatorFn.length > 0) {
55 return curryN(generatorFn.length, asyncWrapper);
56 }
57 return asyncWrapper;
58});
59
60export default async;
Note: See TracBrowser for help on using the repository browser.