index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var thenify = require('thenify')
  2. module.exports = thenifyAll
  3. thenifyAll.withCallback = withCallback
  4. thenifyAll.thenify = thenify
  5. /**
  6. * Promisifies all the selected functions in an object.
  7. *
  8. * @param {Object} source the source object for the async functions
  9. * @param {Object} [destination] the destination to set all the promisified methods
  10. * @param {Array} [methods] an array of method names of `source`
  11. * @return {Object}
  12. * @api public
  13. */
  14. function thenifyAll(source, destination, methods) {
  15. return promisifyAll(source, destination, methods, thenify)
  16. }
  17. /**
  18. * Promisifies all the selected functions in an object and backward compatible with callback.
  19. *
  20. * @param {Object} source the source object for the async functions
  21. * @param {Object} [destination] the destination to set all the promisified methods
  22. * @param {Array} [methods] an array of method names of `source`
  23. * @return {Object}
  24. * @api public
  25. */
  26. function withCallback(source, destination, methods) {
  27. return promisifyAll(source, destination, methods, thenify.withCallback)
  28. }
  29. function promisifyAll(source, destination, methods, promisify) {
  30. if (!destination) {
  31. destination = {};
  32. methods = Object.keys(source)
  33. }
  34. if (Array.isArray(destination)) {
  35. methods = destination
  36. destination = {}
  37. }
  38. if (!methods) {
  39. methods = Object.keys(source)
  40. }
  41. if (typeof source === 'function') destination = promisify(source)
  42. methods.forEach(function (name) {
  43. // promisify only if it's a function
  44. if (typeof source[name] === 'function') destination[name] = promisify(source[name])
  45. })
  46. // proxy the rest
  47. Object.keys(source).forEach(function (name) {
  48. if (deprecated(source, name)) return
  49. if (destination[name]) return
  50. destination[name] = source[name]
  51. })
  52. return destination
  53. }
  54. function deprecated(source, name) {
  55. var desc = Object.getOwnPropertyDescriptor(source, name)
  56. if (!desc || !desc.get) return false
  57. if (desc.get.name === 'deprecated') return true
  58. return false
  59. }