forked from a-synchronous/rubico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fork.js
91 lines (88 loc) · 2.18 KB
/
fork.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const isArray = require('./_internal/isArray')
const funcAll = require('./_internal/funcAll')
const funcObjectAll = require('./_internal/funcObjectAll')
const funcAllSeries = require('./_internal/funcAllSeries')
/**
* @name fork
*
* @synopsis
* ```coffeescript [specscript]
* var args ...any,
* funcsArray Array<...args=>Promise|any>,
* funcsObject Object<...args=>Promise|any>
*
* fork(funcsArray)(...args) -> parallelized Promise|Array
*
* fork(funcsObject)(...args) -> parallelized Promise|Object
* ```
*
* @description
* Run an array or object of functions in parallel, returning an array or object result.
*
* ```javascript [playground]
* console.log(
* fork({
* greetings: fork([
* greeting => greeting + ' world',
* greeting => greeting + ' mom',
* ]),
* })('hello'),
* ) // { greetings: ['hello world', 'hello mom'] }
* ```
*
* Use `fork` to simultaneously compose objects and handle async.
*
* ```javascript [playground]
* const identity = value => value
*
* const userbase = new Map()
* userbase.set('1', { _id: 1, name: 'George' })
*
* const getUserByID = async id => userbase.get(id)
*
* pipe([
* fork({
* id: identity,
* user: getUserByID,
* }),
* tap(({ id, user }) => {
* console.log(`Got user ${JSON.stringify(user)} by id ${id}`)
* }),
* ])('1')
* ```
*
* @execution concurrent
*/
const fork = funcs => isArray(funcs) ? funcAll(funcs) : funcObjectAll(funcs)
/**
* @name fork.series
*
* @synopsis
* ```coffeescript [specscript]
* var args ...any,
* funcs Array<...args=>Promise|any>
*
* fork.series(funcs)(...args) => forkedInSeries Promise|Array
* ```
*
* @description
* `fork` with serial execution.
*
* ```javascript [playground]
* const sleep = ms => () => new Promise(resolve => setTimeout(resolve, ms))
*
* fork.series([
* greeting => console.log(greeting + ' world'),
* sleep(1000),
* greeting => console.log(greeting + ' mom'),
* sleep(1000),
* greeting => console.log(greeting + ' darkness'),
* ])('hello') // hello world
* // hello mom
* // hello darkness
* ```
*
* @execution series
*/
fork.series = funcAllSeries
module.exports = fork