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.

76 lines
2.0 KiB

4 years ago
  1. # universalify
  2. [![Travis branch](https://img.shields.io/travis/RyanZim/universalify/master.svg)](https://travis-ci.org/RyanZim/universalify)
  3. ![Coveralls github branch](https://img.shields.io/coveralls/github/RyanZim/universalify/master.svg)
  4. ![npm](https://img.shields.io/npm/dm/universalify.svg)
  5. ![npm](https://img.shields.io/npm/l/universalify.svg)
  6. Make a callback- or promise-based function support both promises and callbacks.
  7. Uses the native promise implementation.
  8. ## Installation
  9. ```bash
  10. npm install universalify
  11. ```
  12. ## API
  13. ### `universalify.fromCallback(fn)`
  14. Takes a callback-based function to universalify, and returns the universalified function.
  15. Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with more than three arguments, and does not ensure that the callback is only called once.
  16. ```js
  17. function callbackFn (n, cb) {
  18. setTimeout(() => cb(null, n), 15)
  19. }
  20. const fn = universalify.fromCallback(callbackFn)
  21. // Works with Promises:
  22. fn('Hello World!')
  23. .then(result => console.log(result)) // -> Hello World!
  24. .catch(error => console.error(error))
  25. // Works with Callbacks:
  26. fn('Hi!', (error, result) => {
  27. if (error) return console.error(error)
  28. console.log(result)
  29. // -> Hi!
  30. })
  31. ```
  32. ### `universalify.fromPromise(fn)`
  33. Takes a promise-based function to universalify, and returns the universalified function.
  34. Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned.
  35. ```js
  36. function promiseFn (n) {
  37. return new Promise(resolve => {
  38. setTimeout(() => resolve(n), 15)
  39. })
  40. }
  41. const fn = universalify.fromPromise(promiseFn)
  42. // Works with Promises:
  43. fn('Hello World!')
  44. .then(result => console.log(result)) // -> Hello World!
  45. .catch(error => console.error(error))
  46. // Works with Callbacks:
  47. fn('Hi!', (error, result) => {
  48. if (error) return console.error(error)
  49. console.log(result)
  50. // -> Hi!
  51. })
  52. ```
  53. ## License
  54. MIT