Deferred.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. "use strict";
  2. var Promise = require("./Promise");
  3. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  4. /**
  5. * Copyright (c) 2013-present, Facebook, Inc.
  6. *
  7. * This source code is licensed under the MIT license found in the
  8. * LICENSE file in the root directory of this source tree.
  9. *
  10. * @typechecks
  11. *
  12. */
  13. /**
  14. * Deferred provides a Promise-like API that exposes methods to resolve and
  15. * reject the Promise. It is most useful when converting non-Promise code to use
  16. * Promises.
  17. *
  18. * If you want to export the Promise without exposing access to the resolve and
  19. * reject methods, you should export `getPromise` which returns a Promise with
  20. * the same semantics excluding those methods.
  21. */
  22. var Deferred =
  23. /*#__PURE__*/
  24. function () {
  25. function Deferred() {
  26. var _this = this;
  27. _defineProperty(this, "_settled", void 0);
  28. _defineProperty(this, "_promise", void 0);
  29. _defineProperty(this, "_resolve", void 0);
  30. _defineProperty(this, "_reject", void 0);
  31. this._settled = false;
  32. this._promise = new Promise(function (resolve, reject) {
  33. _this._resolve = resolve;
  34. _this._reject = reject;
  35. });
  36. }
  37. var _proto = Deferred.prototype;
  38. _proto.getPromise = function getPromise() {
  39. return this._promise;
  40. };
  41. _proto.resolve = function resolve(value) {
  42. this._settled = true;
  43. this._resolve(value);
  44. };
  45. _proto.reject = function reject(reason) {
  46. this._settled = true;
  47. this._reject(reason);
  48. };
  49. _proto["catch"] = function _catch(onReject) {
  50. return Promise.prototype["catch"].apply(this._promise, arguments);
  51. };
  52. _proto.then = function then(onFulfill, onReject) {
  53. return Promise.prototype.then.apply(this._promise, arguments);
  54. };
  55. _proto.done = function done(onFulfill, onReject) {
  56. // Embed the polyfill for the non-standard Promise.prototype.done so that
  57. // users of the open source fbjs don't need a custom lib for Promise
  58. var promise = arguments.length ? this._promise.then.apply(this._promise, arguments) : this._promise;
  59. promise.then(undefined, function (err) {
  60. setTimeout(function () {
  61. throw err;
  62. }, 0);
  63. });
  64. };
  65. _proto.isSettled = function isSettled() {
  66. return this._settled;
  67. };
  68. return Deferred;
  69. }();
  70. module.exports = Deferred;