PromiseMap.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. *
  8. */
  9. 'use strict';
  10. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11. var Deferred = require('./Deferred');
  12. var invariant = require('./invariant');
  13. /**
  14. * A map of asynchronous values that can be get or set in any order. Unlike a
  15. * normal map, setting the value for a particular key more than once throws.
  16. * Also unlike a normal map, a key can either be resolved or rejected.
  17. */
  18. var PromiseMap = function () {
  19. function PromiseMap() {
  20. _classCallCheck(this, PromiseMap);
  21. this._deferred = {};
  22. }
  23. PromiseMap.prototype.get = function get(key) {
  24. return getDeferred(this._deferred, key).getPromise();
  25. };
  26. PromiseMap.prototype.resolveKey = function resolveKey(key, value) {
  27. var entry = getDeferred(this._deferred, key);
  28. !!entry.isSettled() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'PromiseMap: Already settled `%s`.', key) : invariant(false) : void 0;
  29. entry.resolve(value);
  30. };
  31. PromiseMap.prototype.rejectKey = function rejectKey(key, reason) {
  32. var entry = getDeferred(this._deferred, key);
  33. !!entry.isSettled() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'PromiseMap: Already settled `%s`.', key) : invariant(false) : void 0;
  34. entry.reject(reason);
  35. };
  36. return PromiseMap;
  37. }();
  38. function getDeferred(entries, key) {
  39. if (!entries.hasOwnProperty(key)) {
  40. entries[key] = new Deferred();
  41. }
  42. return entries[key];
  43. }
  44. module.exports = PromiseMap;