UNPKG

2.53 kBMarkdownView Raw
1[![npm][npm]][npm-url]
2[![deps][deps]][deps-url]
3[![size][size]][size-url]
4
5# @subiz/flow
6
7Just a few simple functions to help you write asynchronous functions easier
8
9* **sleep**, pauses the current execution flow for a specific milliseconds.
10* **loop**, repeatly calls a function until it returns false.
11* **map**, runs a function concurrently on every items of the given collection.
12* **batch**, executes a function agains a stream of jobs (unbounded) in windowed fashion.
13
14### Installing
15```sh
16npm i --save @subiz/flow
17```
18
19### Examples
20#### Sleep
21Sleep pauses the current execution flow
22```js
23var flow = require('@subiz/flow')
24
25console.log('sleeping for 1 sec')
26await flow.sleep(1000)
27console.log('ok, I am up')
28```
29
30#### Loop
31Loop is just like do/while, but it runs on both sync and async function
32```js
33var flow = require('@subiz/flow')
34
35var n = 0
36// call an async function 10 times
37await flow.loop(async () => {
38 await flow.sleep(10)
39
40 n++
41 if (n === 10) return false
42 return true
43})
44
45console.log(n) // 10
46```
47*Caution:* The above code is just a super complicated version of
48```js
49for (var i = 0; i < 10; i++) await doSomethind()
50```
51The **loop** function only make sense when you have to write code that run on older browsers which do not support `async/await` (and you hate babel). Here is an example of asynchronous looping without `async/await`
52
53```js
54var n = 0
55// call a async function 10 times
56flow.loop(function() {
57 return flow.sleep(10).then(function() {
58 n++
59 return n === 10
60 })
61}).then(function() {
62 console.log(n) // 10
63})
64```
65But again, please do not use this function when a simple for-loop will do.
66
67#### Map
68Map is like js `array.prototype.map` but run concurrently.
69```js
70var flow = require('@subiz/flow')
71
72outs = await flow.map([1, 2, 3, 4], 2, async i => {
73 await flow.sleep(1000)
74 return i * 2
75})
76
77// after 2 seconds
78console.log(outs) // [2, 4, 6, 8]
79```
80On the example above, we have 4 items to process, each item need 1 second to process. With concurrency level of 2, it would only takes 2 seconds to finish.
81
82#### Batch
83
84
85### References
86#### sleep(ms)
87#### loop(func)
88
89#### map(collections, concurrencyLevel, func)
90#### batch(maxItemsPerBatch, delayMilliseconds, func)
91
92
93[npm]: https://img.shields.io/npm/v/@subiz/flow.svg
94[npm-url]: https://npmjs.com/package/@subiz/flow
95[deps]: https://david-dm.org/@subiz/flow.svg
96[deps-url]: https://david-dm.org/@subiz/flow
97[size]: https://packagephobia.now.sh/badge?p=@subiz/flow
98[size-url]: https://packagephobia.now.sh/result?p=@subiz/flow