Promise.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. *
  3. */
  4. export class Deferred<T = any> {
  5. private _promise: Promise<T> = null!;
  6. private _resolve: (value: T | PromiseLike<T>) => void = null!;
  7. private _reject: (reason?: any) => void = null!;
  8. constructor() {
  9. let self = this;
  10. self._promise = new Promise((resolve, reject) => {
  11. self._resolve = resolve;
  12. self._reject = reject;
  13. });
  14. }
  15. get promise(): Promise<T> { return this._promise; }
  16. resolve(value?: T) {
  17. if (this._resolve) {
  18. this._resolve.call(this._promise, value);
  19. this._resolve = null;
  20. }
  21. }
  22. reject(reason?: any) {
  23. if (this._reject) {
  24. this._reject.call(this._promise, reason);
  25. this._reject = null;
  26. }
  27. }
  28. }
  29. /**
  30. * 执行 n 次 resolve 后才执行真正的 resolve
  31. * 允许在执行前动态的添加执行次数
  32. */
  33. export class NDeferred<T = any> {
  34. private _promise: Promise<T> = null!;
  35. private _resolve: (value: T | PromiseLike<T>) => void = null!;
  36. private _reject: (reason?: any) => void = null!;
  37. private m_Cnt: number = 0;
  38. static Create<TT>(cnt: number): NDeferred<TT> { return new NDeferred<TT>(cnt); }
  39. private constructor(cnt: number) {
  40. const that = this;
  41. if (cnt <= 0) {
  42. throw "[NDeferred] 执行次数必须大于 0";
  43. }
  44. that.m_Cnt = cnt;
  45. that._promise = new Promise((resolve, reject) => {
  46. that._resolve = (p: T) => {
  47. if (that.m_Cnt <= 0) {
  48. return;
  49. };
  50. --that.m_Cnt;
  51. if (that.m_Cnt === 0) {
  52. resolve(p)
  53. }
  54. };
  55. that._reject = reject;
  56. });
  57. }
  58. /**
  59. * 动态增加执行所需次数
  60. */
  61. add() {
  62. const that = this;
  63. if (that.m_Cnt > 0) {
  64. ++that.m_Cnt;
  65. } else {
  66. throw "[NDeferred] 执行次数等于 0,表明 promise 已 resolve,不能再动态添加执行次数";
  67. }
  68. }
  69. addCnt(cnt: number) {
  70. const that = this;
  71. if (that.m_Cnt > 0) {
  72. that.m_Cnt += cnt;
  73. } else {
  74. throw "[NDeferred] 执行次数等于 0,表明 promise 已 resolve,不能再动态添加执行次数";
  75. }
  76. }
  77. get promise(): Promise<T> { return this._promise; }
  78. resolve(value?: T) { this._resolve.call(this._promise, value); }
  79. reject(reason?: any) { this._reject.call(this._promise, reason); }
  80. }