Advertisement
Guest User

Untitled

a guest
May 19th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. const delay = (callback) => setTimeout(callback, 0);
  2.  
  3. const STATEMAP = {
  4. PENDING: 0,
  5. FULFILLED: 1,
  6. REJECTED: 2,
  7. }
  8.  
  9. class _Promise {
  10. constructor(callback) {
  11. this._state = STATEMAP.PENDING;
  12. this._worker = callback;
  13. this._handlers = [];
  14. this._resolve = (value) => {
  15. this._value = value;
  16. this._state = STATEMAP.FULFILLED;
  17. this._handlers.forEach((obj) => {
  18. this._runHandler(obj.onFulfilled, obj.onRejected);
  19. });
  20. };
  21. this._reject = (error) => {
  22. this._error = error;
  23. this._state = STATEMAP.REJECTED;
  24. this._handlers.forEach((obj) => {
  25. this._runHandler(obj.onFulfilled, obj.onRejected);
  26. });
  27. }
  28. this._run();
  29. }
  30.  
  31. _run() {
  32. if (this._worker) {
  33. try {
  34. this._worker(this._resolve, this._reject);
  35. } catch (err) {
  36. this._reject(err);
  37. }
  38. }
  39. }
  40.  
  41. _runHandler(onFulfilled, onRejected) {
  42. if (this._state === STATEMAP.PENDING) {
  43. this._handlers.push({onFulfilled, onRejected});
  44. } else {
  45. if (this._state === STATEMAP.FULFILLED) {
  46. onFulfilled(this._value);
  47. } else if (this._state === STATEMAP.REJECTED) {
  48. onRejected(this._error);
  49. }
  50. }
  51. }
  52.  
  53. then(onSucceeded, onFailed) {
  54. const self = this;
  55. const callback = (resolve, reject) => delay(() => {
  56. self._runHandler((value) => {
  57. try {
  58. if (onSucceeded) {
  59. resolve(onSucceeded(value));
  60. } else {
  61. resolve(value);
  62. }
  63. } catch (e) {
  64. reject(e);
  65. }
  66. }, (error) => {
  67. try {
  68. if (onFailed) {
  69. reject(onFailed(error));
  70. } else {
  71. reject(error);
  72. }
  73. } catch (e) {
  74. reject(e);
  75. }
  76. });
  77. });
  78. return new _Promise(callback);
  79. }
  80.  
  81. catch(onFailed) {
  82. this._onRejected = onFailed;
  83. const self = this;
  84. const callback = (resolve, reject) => delay(() => {
  85. self._runHandler(() => {},
  86. (error) => {
  87. try {
  88. if (onFailed) {
  89. reject(onFailed(error));
  90. } else {
  91. reject(error);
  92. }
  93. } catch (e) {
  94. reject(e);
  95. }
  96. });
  97. });
  98. return new _Promise(callback);
  99. }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement