You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.4 KiB

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