Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. function MyPromise(fn) {
  2. let status = 0; // 0 = unfulfilled, 1 = resolved, 2 = rejected
  3.  
  4. function makeQueue(neededStatus) {
  5. return {
  6. neededStatus,
  7. fns: [],
  8. do() {
  9. if (status === neededStatus) {
  10. if (neededStatus === 2 && this.fns.length === 0) {
  11. console.error('uncaught error');
  12. }
  13. while(this.fns.length) {
  14. this.fns.shift()(this.value);
  15. }
  16. }
  17. },
  18. handle(v) {
  19. if (status) throw Error('can not set, already handled');
  20. status = neededStatus;
  21. this.value = v;
  22. this.do();
  23. },
  24. };
  25. }
  26.  
  27. const thenQueue = makeQueue(1);
  28. const catchQueue = makeQueue(2);
  29. const resolve = thenQueue.handle.bind(thenQueue);
  30. const reject = catchQueue.handle.bind(catchQueue);
  31.  
  32. function makeChain(queue) {
  33. return function(fn) {
  34. let fns;
  35. const promise = new MyPromise(function(resolve, reject) {
  36. fns = [undefined, resolve, reject];
  37. });
  38. queue.fns.push(function(r) {
  39. fns[queue.neededStatus](fn(r));
  40. });
  41. queue.do();
  42. return promise;
  43. };
  44. }
  45.  
  46. this.then = makeChain(thenQueue);
  47. this.catch = makeChain(catchQueue);
  48.  
  49. try {
  50. fn(resolve, reject);
  51. } catch (e) {
  52. reject(e);
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement