awaitify.js 796 B

123456789101112131415161718192021222324252627
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = awaitify;
  6. // conditionally promisify a function.
  7. // only return a promise if a callback is omitted
  8. function awaitify(asyncFn, arity = asyncFn.length) {
  9. if (!arity) throw new Error('arity is undefined');
  10. function awaitable(...args) {
  11. if (typeof args[arity - 1] === 'function') {
  12. return asyncFn.apply(this, args);
  13. }
  14. return new Promise((resolve, reject) => {
  15. args[arity - 1] = (err, ...cbArgs) => {
  16. if (err) return reject(err);
  17. resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
  18. };
  19. asyncFn.apply(this, args);
  20. });
  21. }
  22. return awaitable;
  23. }
  24. module.exports = exports['default'];