source: trip-planner-front/node_modules/thunky/README.md

Last change on this file was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.4 KB
Line 
1# thunky
2
3Delay the evaluation of a paramless async function and cache the result (see [thunk](http://en.wikipedia.org/wiki/Thunk_%28functional_programming%29)).
4
5```
6npm install thunky
7```
8
9[![build status](http://img.shields.io/travis/mafintosh/thunky.svg?style=flat)](http://travis-ci.org/mafintosh/thunky)
10
11## Example
12
13Let's make a simple function that returns a random number 1 second after it is called for the first time
14
15``` js
16var thunky = require('thunky')
17
18var test = thunky(function (callback) { // the inner function should only accept a callback
19 console.log('waiting 1s and returning random number')
20 setTimeout(function () {
21 callback(Math.random())
22 }, 1000)
23})
24
25test(function (num) { // inner function is called the first time we call test
26 console.log(num) // prints random number
27})
28
29test(function (num) { // subsequent calls waits for the first call to finish and return the same value
30 console.log(num) // prints the same random number as above
31})
32```
33
34## Lazy evaluation
35
36Thunky makes it easy to implement a lazy evaluation pattern.
37
38``` js
39var getDb = thunky(function (callback) {
40 db.open(myConnectionString, callback)
41})
42
43var queryDb = function (query, callback) {
44 getDb(function (err, db) {
45 if (err) return callback(err)
46 db.query(query, callback)
47 })
48}
49
50queryDb('some query', function (err, result) { ... } )
51
52queryDb('some other query', function (err, result) { ... } )
53```
54
55The first time `getDb` is called it will try do open a connection to the database.
56Any subsequent calls will just wait for the first call to complete and then call your callback.
57
58A nice property of this pattern is that it *easily* allows us to pass any error caused by `getDb` to the `queryDb` callback.
59
60## Error → No caching
61
62If the thunk callback is called with an `Error` object as the first argument it will not cache the result
63
64``` js
65var fails = thunky(function (callback) {
66 console.log('returning an error')
67 callback(new Error('bad stuff'))
68})
69
70fails(function (err) { // inner function is called
71 console.log(err)
72});
73
74fails(function (err) { // inner function is called again as it returned an error before
75 console.log(err)
76})
77```
78
79## Promise version
80
81A promise version is available as well
82
83``` js
84var thunkyp = require('thunky/promise')
85
86var ready = thunkyp(async function () {
87 // ... do async stuff
88 return 42
89})
90
91// same semantics as the callback version
92await ready()
93```
94
95## License
96
97MIT
Note: See TracBrowser for help on using the repository browser.