39cb88c2469aea23c4835876b3ca034ac8046500b71225a7d318d70feab8e834b68257d144d0658f75d2519353f057b4e8c840bf4fa97a78e84c052f1a906b 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # @gar/promisify
  2. ### Promisify an entire object or class instance
  3. This module leverages es6 Proxy and Reflect to promisify every function in an
  4. object or class instance.
  5. It assumes the callback that the function is expecting is the last
  6. parameter, and that it is an error-first callback with only one value,
  7. i.e. `(err, value) => ...`. This mirrors node's `util.promisify` method.
  8. In order that you can use it as a one-stop-shop for all your promisify
  9. needs, you can also pass it a function. That function will be
  10. promisified as normal using node's built-in `util.promisify` method.
  11. [node's custom promisified
  12. functions](https://nodejs.org/api/util.html#util_custom_promisified_functions)
  13. will also be mirrored, further allowing this to be a drop-in replacement
  14. for the built-in `util.promisify`.
  15. ### Examples
  16. Promisify an entire object
  17. ```javascript
  18. const promisify = require('@gar/promisify')
  19. class Foo {
  20. constructor (attr) {
  21. this.attr = attr
  22. }
  23. double (input, cb) {
  24. cb(null, input * 2)
  25. }
  26. const foo = new Foo('baz')
  27. const promisified = promisify(foo)
  28. console.log(promisified.attr)
  29. console.log(await promisified.double(1024))
  30. ```
  31. Promisify a function
  32. ```javascript
  33. const promisify = require('@gar/promisify')
  34. function foo (a, cb) {
  35. if (a !== 'bad') {
  36. return cb(null, 'ok')
  37. }
  38. return cb('not ok')
  39. }
  40. const promisified = promisify(foo)
  41. // This will resolve to 'ok'
  42. promisified('good')
  43. // this will reject
  44. promisified('bad')
  45. ```