Deferred.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. "use strict";
  2. var Promise = require("./Promise");
  3. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  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 = function () {
  23. function Deferred() {
  24. var _this = this;
  25. _classCallCheck(this, Deferred);
  26. this._settled = false;
  27. this._promise = new Promise(function (resolve, reject) {
  28. _this._resolve = resolve;
  29. _this._reject = reject;
  30. });
  31. }
  32. Deferred.prototype.getPromise = function getPromise() {
  33. return this._promise;
  34. };
  35. Deferred.prototype.resolve = function resolve(value) {
  36. this._settled = true;
  37. this._resolve(value);
  38. };
  39. Deferred.prototype.reject = function reject(reason) {
  40. this._settled = true;
  41. this._reject(reason);
  42. };
  43. Deferred.prototype["catch"] = function _catch(onReject) {
  44. return Promise.prototype["catch"].apply(this._promise, arguments);
  45. };
  46. Deferred.prototype.then = function then(onFulfill, onReject) {
  47. return Promise.prototype.then.apply(this._promise, arguments);
  48. };
  49. Deferred.prototype.done = function done(onFulfill, onReject) {
  50. // Embed the polyfill for the non-standard Promise.prototype.done so that
  51. // users of the open source fbjs don't need a custom lib for Promise
  52. var promise = arguments.length ? this._promise.then.apply(this._promise, arguments) : this._promise;
  53. promise.then(undefined, function (err) {
  54. setTimeout(function () {
  55. throw err;
  56. }, 0);
  57. });
  58. };
  59. Deferred.prototype.isSettled = function isSettled() {
  60. return this._settled;
  61. };
  62. return Deferred;
  63. }();
  64. module.exports = Deferred;