Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.13 KB | None | 0 0
  1. class PromiseX {
  2. constructor(func) {
  3. this.status = 'pending';
  4. this.resolvers = [];
  5. this.rejecters = [];
  6.  
  7. const resolve = (value) => {
  8. if (this.status !== 'pending') {
  9. return;
  10. }
  11. this.status = 'resolved';
  12. this.value = value;
  13. this.resolvers.forEach((resolver) => resolver(value));
  14. };
  15. const reject = (value) => {
  16. if (this.status !== 'pending') {
  17. return;
  18. }
  19. this.status = 'rejected';
  20. this.value = value;
  21. this.rejecters.forEach((rejecter) => rejecter(value));
  22. };
  23.  
  24. try {
  25. func(resolve, reject);
  26. } catch (e) {
  27. reject(e);
  28. }
  29.  
  30. this.then = (onFulfilled, onRejected) => {
  31. return new PromiseX((thenResolve, thenReject) => {
  32. this.resolvers.push((value) => {
  33. if (typeof onFulfilled !== 'function') {
  34. thenResolve(value);
  35.  
  36. return;
  37. }
  38.  
  39. try {
  40. const nextValue = onFulfilled(value);
  41.  
  42. if (nextValue instanceof PromiseX) {
  43. nextValue.then((value) => thenResolve(value));
  44. } else {
  45. thenResolve(nextValue);
  46. }
  47. } catch (error) {
  48. thenReject(error);
  49. }
  50. });
  51. this.rejecters.push((value) => {
  52. if (typeof onRejected !== 'function') {
  53. thenReject(value);
  54.  
  55. return;
  56. }
  57.  
  58. try {
  59. const nextValue = onRejected(value);
  60.  
  61. if (nextValue instanceof PromiseX) {
  62. nextValue.then((value) => thenResolve(value));
  63. } else {
  64. thenResolve(nextValue);
  65. }
  66. } catch (error) {
  67. thenReject(error);
  68. }
  69. });
  70. });
  71. };
  72.  
  73. this.catch = (onError) => this.then(null, onError);
  74. }
  75.  
  76. static resolve = (value) => new PromiseX((resolve) => resolve(value));
  77.  
  78. static reject = (value) => new PromiseX((resolve, reject) => reject(value));
  79.  
  80. static all = (arrayOfPromises) =>
  81. new PromiseX((resolve, reject) => {
  82. const resolved = [];
  83.  
  84. arrayOfPromises.forEach((promise) => {
  85. promise
  86. .then((value) => {
  87. resolved.push(value);
  88.  
  89. if (resolve.length === arrayOfPromises.length) {
  90. resolve(resolved);
  91. }
  92. })
  93. .catch(reject);
  94. });
  95. });
  96.  
  97. static race = (arrayOfPromises) =>
  98. new PromiseX((resolve, reject) => {
  99. arrayOfPromises.forEach((promise) => {
  100. promise.then(resolve).catch(reject);
  101. });
  102. });
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement