promiseOrCallback.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const PromiseProvider = require('../promise_provider');
  3. const immediate = require('./immediate');
  4. const emittedSymbol = Symbol('mongoose:emitted');
  5. module.exports = function promiseOrCallback(callback, fn, ee, Promise) {
  6. if (typeof callback === 'function') {
  7. return fn(function(error) {
  8. if (error != null) {
  9. if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  10. error[emittedSymbol] = true;
  11. ee.emit('error', error);
  12. }
  13. try {
  14. callback(error);
  15. } catch (error) {
  16. return immediate(() => {
  17. throw error;
  18. });
  19. }
  20. return;
  21. }
  22. callback.apply(this, arguments);
  23. });
  24. }
  25. Promise = Promise || PromiseProvider.get();
  26. return new Promise((resolve, reject) => {
  27. fn(function(error, res) {
  28. if (error != null) {
  29. if (ee != null && ee.listeners != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  30. error[emittedSymbol] = true;
  31. ee.emit('error', error);
  32. }
  33. return reject(error);
  34. }
  35. if (arguments.length > 2) {
  36. return resolve(Array.prototype.slice.call(arguments, 1));
  37. }
  38. resolve(res);
  39. });
  40. });
  41. };