Deferred.js.flow 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. * @providesModule Deferred
  8. * @typechecks
  9. * @flow
  10. */
  11. /**
  12. * Deferred provides a Promise-like API that exposes methods to resolve and
  13. * reject the Promise. It is most useful when converting non-Promise code to use
  14. * Promises.
  15. *
  16. * If you want to export the Promise without exposing access to the resolve and
  17. * reject methods, you should export `getPromise` which returns a Promise with
  18. * the same semantics excluding those methods.
  19. */
  20. class Deferred<Tvalue, Treason> {
  21. _settled: boolean;
  22. _promise: Promise<any>;
  23. _resolve: (value: Tvalue) => void;
  24. _reject: (reason: Treason) => void;
  25. constructor() {
  26. this._settled = false;
  27. this._promise = new Promise((resolve, reject) => {
  28. this._resolve = (resolve: any);
  29. this._reject = (reject: any);
  30. });
  31. }
  32. getPromise(): Promise<any> {
  33. return this._promise;
  34. }
  35. resolve(value: Tvalue): void {
  36. this._settled = true;
  37. this._resolve(value);
  38. }
  39. reject(reason: Treason): void {
  40. this._settled = true;
  41. this._reject(reason);
  42. }
  43. catch(onReject?: ?(error: any) => mixed): Promise<any> {
  44. return Promise.prototype.catch.apply(this._promise, arguments);
  45. }
  46. then(onFulfill?: ?(value: any) => mixed, onReject?: ?(error: any) => mixed): Promise<any> {
  47. return Promise.prototype.then.apply(this._promise, arguments);
  48. }
  49. done(onFulfill?: ?(value: any) => mixed, onReject?: ?(error: any) => mixed): void {
  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. const 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. isSettled(): boolean {
  60. return this._settled;
  61. }
  62. }
  63. module.exports = Deferred;