index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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__$$, options) {
  12. assert(typeof $$__fn__$$ === 'function')
  13. return eval(createWrapper($$__fn__$$.name, options))
  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__$$, options) {
  23. assert(typeof $$__fn__$$ === 'function')
  24. options = options || {}
  25. options.withCallback = true
  26. if (options.multiArgs === undefined) options.multiArgs = true
  27. return eval(createWrapper($$__fn__$$.name, options))
  28. }
  29. function createCallback(resolve, reject, multiArgs) {
  30. return function(err, value) {
  31. if (err) return reject(err)
  32. var length = arguments.length
  33. if (length <= 2 || !multiArgs) return resolve(value)
  34. if (Array.isArray(multiArgs)) {
  35. var values = {}
  36. for (var i = 1; i < length; i++) values[multiArgs[i - 1]] = arguments[i]
  37. return resolve(values)
  38. }
  39. var values = new Array(length - 1)
  40. for (var i = 1; i < length; ++i) values[i - 1] = arguments[i]
  41. resolve(values)
  42. }
  43. }
  44. function createWrapper(name, options) {
  45. name = (name || '').replace(/\s|bound(?!$)/g, '')
  46. options = options || {}
  47. // default to true
  48. var multiArgs = options.multiArgs !== undefined ? options.multiArgs : true
  49. multiArgs = 'var multiArgs = ' + JSON.stringify(multiArgs) + '\n'
  50. var withCallback = options.withCallback ?
  51. 'var lastType = typeof arguments[len - 1]\n'
  52. + 'if (lastType === "function") return $$__fn__$$.apply(self, arguments)\n'
  53. : ''
  54. return '(function ' + name + '() {\n'
  55. + 'var self = this\n'
  56. + 'var len = arguments.length\n'
  57. + multiArgs
  58. + withCallback
  59. + 'var args = new Array(len + 1)\n'
  60. + 'for (var i = 0; i < len; ++i) args[i] = arguments[i]\n'
  61. + 'var lastIndex = i\n'
  62. + 'return new Promise(function (resolve, reject) {\n'
  63. + 'args[lastIndex] = createCallback(resolve, reject, multiArgs)\n'
  64. + '$$__fn__$$.apply(self, args)\n'
  65. + '})\n'
  66. + '})'
  67. }