-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
runtime.js
70 lines (65 loc) · 1.39 KB
/
runtime.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* External dependencies
*/
import { create } from 'rungen';
import { map } from 'lodash';
import isPromise from 'is-promise';
/**
* Internal dependencies
*/
import { isActionOfType, isAction } from './is-action';
/**
* Create a co-routine runtime.
*
* @param {Object} controls Object of control handlers.
* @param {Function} dispatch Unhandled action dispatch.
*
* @return {Function} co-routine runtime
*/
export default function createRuntime( controls = {}, dispatch ) {
const rungenControls = map(
controls,
( control, actionType ) => (
value,
next,
iterate,
yieldNext,
yieldError
) => {
if ( ! isActionOfType( value, actionType ) ) {
return false;
}
const routine = control( value );
if ( isPromise( routine ) ) {
// Async control routine awaits resolution.
routine.then( yieldNext, yieldError );
} else {
yieldNext( routine );
}
return true;
}
);
const unhandledActionControl = ( value, next ) => {
if ( ! isAction( value ) ) {
return false;
}
dispatch( value );
next();
return true;
};
rungenControls.push( unhandledActionControl );
const rungenRuntime = create( rungenControls );
return ( action ) =>
new Promise( ( resolve, reject ) =>
rungenRuntime(
action,
( result ) => {
if ( isAction( result ) ) {
dispatch( result );
}
resolve( result );
},
reject
)
);
}