awaitify.js 816 B

12345678910111213141516171819202122232425262728
  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) {
  9. if (!arity) arity = asyncFn.length;
  10. if (!arity) throw new Error('arity is undefined');
  11. function awaitable(...args) {
  12. if (typeof args[arity - 1] === 'function') {
  13. return asyncFn.apply(this, args);
  14. }
  15. return new Promise((resolve, reject) => {
  16. args[arity - 1] = (err, ...cbArgs) => {
  17. if (err) return reject(err);
  18. resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
  19. };
  20. asyncFn.apply(this, args);
  21. });
  22. }
  23. return awaitable;
  24. }
  25. module.exports = exports.default;