Guest User

Untitled

a guest
Jul 15th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. class MyPromise {
  2. constructor(executor) {
  3. if (typeof executor !== 'function') {
  4. throw new Error('Executor function must be a function');
  5. }
  6.  
  7. this.$state = 'PENDING';
  8. this.$chained = [];
  9.  
  10. const resolve = (res) => {
  11. if (this.$state !== 'PENDING') {
  12. return;
  13. }
  14. this.$state = 'FULFILLED';
  15. this.$internalValue = res;
  16. for (const { onFulfilled } of this.$chained) {
  17. onFulfilled(res);
  18. }
  19. };
  20. const reject = (err) => {
  21. if (this.$state !== 'PENDING') {
  22. }
  23. this.$state = 'REJECTED';
  24. this.$internalValue = err;
  25. for (const { onRejected } of this.$chained) {
  26. onRejected(err);
  27. }
  28. };
  29.  
  30. try {
  31. executor(resolve, reject);
  32. } catch (err) {
  33. reject(err);
  34. }
  35. }
  36.  
  37. then(onFulfilled, onRejected) {
  38. if (this.$state === 'FULFILLED') {
  39. onFulfilled(this.$internalValue);
  40. } else if (this.$state === 'REJECTED') {
  41. onRejected(this.$internalValue);
  42. } else {
  43. this.$chained.push({ onFulfilled, onRejected });
  44. }
  45. }
  46. }
  47.  
  48. const firstPromise = new MyPromise((resolve, reject) => {
  49. setTimeout(() => resolve('wubadubdub'), 1000);
  50. });
  51.  
  52. firstPromise.then(successMessage => console.log(`wahoo ${successMessage}`));
Add Comment
Please, Sign In to add comment