Advertisement
AFF

Simple Promise ES6

AFF
May 21st, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. class PromiseSimple {
  2.  
  3. constructor(executionFunction) {
  4. this.promiseChain = [];
  5. this.handleError = () => {};
  6.  
  7. this.onResolve = this.onResolve.bind(this);
  8. this.onReject = this.onReject.bind(this);
  9.  
  10. executionFunction(this.onResolve, this.onReject);
  11. }
  12.  
  13. then(onResolve) {
  14. this.promiseChain.push(onResolve);
  15.  
  16. return this;
  17. }
  18.  
  19. catch(handleError) {
  20. this.handleError = handleError;
  21.  
  22. return this;
  23. }
  24.  
  25. onResolve(value) {
  26. let storedValue = value;
  27.  
  28. try {
  29. this.promiseChain.forEach((nextFunction) => {
  30. storedValue = nextFunction(storedValue);
  31. });
  32. } catch(error) {
  33. this.promiseChain = [];
  34. this.onReject(error);
  35. }
  36. }
  37.  
  38. onReject(error) {
  39. this.handleError(error);
  40. }
  41. }
  42.  
  43. const myPromise = new PromiseSimple((onResolve, onReject) => {
  44. setTimeout(onResolve, 1000, 'Fine!');
  45. });
  46.  
  47. myPromise.then((response) => {
  48. console.log(response);
  49. }, (error) => {
  50. console.log(error);
  51. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement