index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var Promise = require('any-promise')
  2. var assert = require('assert')
  3. module.exports = thenify
  4. /**
  5. * Turn async functions into promises
  6. *
  7. * @param {Function} $$__fn__$$
  8. * @return {Function}
  9. * @api public
  10. */
  11. function thenify($$__fn__$$) {
  12. assert(typeof $$__fn__$$ === 'function')
  13. return eval(createWrapper($$__fn__$$.name.replace(/\s|bound(?!$)/g,'')))
  14. }
  15. /**
  16. * Turn async functions into promises and backward compatible with callback
  17. *
  18. * @param {Function} $$__fn__$$
  19. * @return {Function}
  20. * @api public
  21. */
  22. thenify.withCallback = function ($$__fn__$$) {
  23. assert(typeof $$__fn__$$ === 'function')
  24. return eval(createWrapper($$__fn__$$.name, true))
  25. }
  26. function createCallback(resolve, reject) {
  27. return function(err, value) {
  28. if (err) return reject(err)
  29. var length = arguments.length
  30. if (length <= 2) return resolve(value)
  31. var values = new Array(length - 1)
  32. for (var i = 1; i < length; ++i) values[i - 1] = arguments[i]
  33. resolve(values)
  34. }
  35. }
  36. function createWrapper(name, withCallback) {
  37. withCallback = withCallback ?
  38. 'var lastType = typeof arguments[len - 1]\n'
  39. + 'if (lastType === "function") return $$__fn__$$.apply(self, arguments)\n'
  40. : ''
  41. return '(function ' + (name || '') + '() {\n'
  42. + 'var self = this\n'
  43. + 'var len = arguments.length\n'
  44. + withCallback
  45. + 'var args = new Array(len + 1)\n'
  46. + 'for (var i = 0; i < len; ++i) args[i] = arguments[i]\n'
  47. + 'var lastIndex = i\n'
  48. + 'return new Promise(function (resolve, reject) {\n'
  49. + 'args[lastIndex] = createCallback(resolve, reject)\n'
  50. + '$$__fn__$$.apply(self, args)\n'
  51. + '})\n'
  52. + '})'
  53. }