index.js 712 B

123456789101112131415161718192021222324
  1. 'use strict'
  2. exports.fromCallback = function (fn) {
  3. return Object.defineProperty(function (...args) {
  4. if (typeof args[args.length - 1] === 'function') fn.apply(this, args)
  5. else {
  6. return new Promise((resolve, reject) => {
  7. fn.call(
  8. this,
  9. ...args,
  10. (err, res) => (err != null) ? reject(err) : resolve(res)
  11. )
  12. })
  13. }
  14. }, 'name', { value: fn.name })
  15. }
  16. exports.fromPromise = function (fn) {
  17. return Object.defineProperty(function (...args) {
  18. const cb = args[args.length - 1]
  19. if (typeof cb !== 'function') return fn.apply(this, args)
  20. else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb)
  21. }, 'name', { value: fn.name })
  22. }