adapter.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @class PromiseAdapter
  3. * @description
  4. * Adapter for the primary promise operations.
  5. *
  6. * Provides compatibility with promise libraries that cannot be recognized automatically,
  7. * via functions that implement the primary operations with promises:
  8. *
  9. * - construct a new promise with a callback function
  10. * - resolve a promise with some result data
  11. * - reject a promise with a reason
  12. *
  13. * #### Example
  14. *
  15. * Below is an example of setting up a [client-side]{@tutorial client} adapter for AngularJS $q.
  16. *
  17. * ```js
  18. * const spexLib = require('spex'); // or include client-side spex.js
  19. *
  20. * const adapter = new spexLib.PromiseAdapter(
  21. * cb => $q(cb), // creating a new promise;
  22. * data => $q.when(data), // resolving a promise;
  23. * reason => $q.reject(reason) // rejecting a promise;
  24. * );
  25. *
  26. * const spex = spexLib(adapter);
  27. * ```
  28. *
  29. * @param {Function} create
  30. * A function that takes a callback parameter and returns a new promise object.
  31. * The callback parameter is expected to be `function(resolve, reject)`.
  32. *
  33. * Passing in anything other than a function will throw `Adapter requires a function to create a promise.`
  34. *
  35. * @param {Function} resolve
  36. * A function that takes an optional data parameter and resolves a promise with it.
  37. *
  38. * Passing in anything other than a function will throw `Adapter requires a function to resolve a promise.`
  39. *
  40. * @param {Function} reject
  41. * A function that takes an optional error parameter and rejects a promise with it.
  42. *
  43. * Passing in anything other than a function will throw `Adapter requires a function to reject a promise.`
  44. *
  45. * @see {@tutorial client}
  46. *
  47. */
  48. class PromiseAdapter {
  49. constructor(create, resolve, reject) {
  50. this.create = create;
  51. this.resolve = resolve;
  52. this.reject = reject;
  53. if (typeof create !== 'function') {
  54. throw new TypeError('Adapter requires a function to create a promise.');
  55. }
  56. if (typeof resolve !== 'function') {
  57. throw new TypeError('Adapter requires a function to resolve a promise.');
  58. }
  59. if (typeof reject !== 'function') {
  60. throw new TypeError('Adapter requires a function to reject a promise.');
  61. }
  62. }
  63. }
  64. module.exports = PromiseAdapter;