promise-parser.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (c) 2015-present, Vitaly Tomilov
  3. *
  4. * See the LICENSE file at the top-level directory of this distribution
  5. * for licensing information.
  6. *
  7. * Removal or modification of this copyright notice is prohibited.
  8. */
  9. const {PromiseAdapter} = require('./promise-adapter');
  10. //////////////////////////////////////////
  11. // Parses and validates a promise library;
  12. function parse(pl) {
  13. let promise;
  14. if (pl instanceof PromiseAdapter) {
  15. promise = function (func) {
  16. return pl.create(func);
  17. };
  18. promise.resolve = pl.resolve;
  19. promise.reject = pl.reject;
  20. promise.all = pl.all;
  21. return promise;
  22. }
  23. const t = typeof pl;
  24. if (t === 'function' || t === 'object') {
  25. const Root = typeof pl.Promise === 'function' ? pl.Promise : pl;
  26. promise = function (func) {
  27. return new Root(func);
  28. };
  29. promise.resolve = Root.resolve;
  30. promise.reject = Root.reject;
  31. promise.all = Root.all;
  32. if (typeof promise.resolve === 'function' &&
  33. typeof promise.reject === 'function' &&
  34. typeof promise.all === 'function') {
  35. return promise;
  36. }
  37. }
  38. throw new TypeError('Invalid promise library specified.');
  39. }
  40. function parsePromise(promiseLib) {
  41. const result = {promiseLib};
  42. if (promiseLib) {
  43. result.promise = parse(promiseLib);
  44. } else {
  45. result.promise = parse(Promise);
  46. result.promiseLib = Promise;
  47. }
  48. return result;
  49. }
  50. module.exports = {parsePromise};