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.

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict'
  2. const { promisify } = require('util')
  3. const handler = {
  4. get: function (target, prop, receiver) {
  5. if (typeof target[prop] !== 'function') {
  6. return target[prop]
  7. }
  8. if (target[prop][promisify.custom]) {
  9. return function () {
  10. return Reflect.get(target, prop, receiver)[promisify.custom].apply(target, arguments)
  11. }
  12. }
  13. return function () {
  14. return new Promise((resolve, reject) => {
  15. Reflect.get(target, prop, receiver).apply(target, [...arguments, function (err, result) {
  16. if (err) {
  17. return reject(err)
  18. }
  19. resolve(result)
  20. }])
  21. })
  22. }
  23. }
  24. }
  25. module.exports = function (thingToPromisify) {
  26. if (typeof thingToPromisify === 'function') {
  27. return promisify(thingToPromisify)
  28. }
  29. if (typeof thingToPromisify === 'object') {
  30. return new Proxy(thingToPromisify, handler)
  31. }
  32. throw new TypeError('Can only promisify functions or objects')
  33. }