[d24f17c] | 1 | import { curryN, bind } from 'ramda';
|
---|
| 2 |
|
---|
| 3 | import resolveP from './resolveP';
|
---|
| 4 | import 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 | */
|
---|
| 32 | const 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 |
|
---|
| 60 | export default async;
|
---|