loader.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. "use strict"
  2. // global key for user preferred registration
  3. var REGISTRATION_KEY = '@@any-promise/REGISTRATION',
  4. // Prior registration (preferred or detected)
  5. registered = null
  6. /**
  7. * Registers the given implementation. An implementation must
  8. * be registered prior to any call to `require("any-promise")`,
  9. * typically on application load.
  10. *
  11. * If called with no arguments, will return registration in
  12. * following priority:
  13. *
  14. * For Node.js:
  15. *
  16. * 1. Previous registration
  17. * 2. global.Promise if node.js version >= 0.12
  18. * 3. Auto detected promise based on first sucessful require of
  19. * known promise libraries. Note this is a last resort, as the
  20. * loaded library is non-deterministic. node.js >= 0.12 will
  21. * always use global.Promise over this priority list.
  22. * 4. Throws error.
  23. *
  24. * For Browser:
  25. *
  26. * 1. Previous registration
  27. * 2. window.Promise
  28. * 3. Throws error.
  29. *
  30. * Options:
  31. *
  32. * Promise: Desired Promise constructor
  33. * global: Boolean - Should the registration be cached in a global variable to
  34. * allow cross dependency/bundle registration? (default true)
  35. */
  36. module.exports = function(root, loadImplementation){
  37. return function register(implementation, opts){
  38. implementation = implementation || null
  39. opts = opts || {}
  40. // global registration unless explicitly {global: false} in options (default true)
  41. var registerGlobal = opts.global !== false;
  42. // load any previous global registration
  43. if(registered === null && registerGlobal){
  44. registered = root[REGISTRATION_KEY] || null
  45. }
  46. if(registered !== null
  47. && implementation !== null
  48. && registered.implementation !== implementation){
  49. // Throw error if attempting to redefine implementation
  50. throw new Error('any-promise already defined as "'+registered.implementation+
  51. '". You can only register an implementation before the first '+
  52. ' call to require("any-promise") and an implementation cannot be changed')
  53. }
  54. if(registered === null){
  55. // use provided implementation
  56. if(implementation !== null && typeof opts.Promise !== 'undefined'){
  57. registered = {
  58. Promise: opts.Promise,
  59. implementation: implementation
  60. }
  61. } else {
  62. // require implementation if implementation is specified but not provided
  63. registered = loadImplementation(implementation)
  64. }
  65. if(registerGlobal){
  66. // register preference globally in case multiple installations
  67. root[REGISTRATION_KEY] = registered
  68. }
  69. }
  70. return registered
  71. }
  72. }