Guest User

Untitled

a guest
Feb 18th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. const states = {
  2. pending: 'Pending',
  3. resolved: 'Resolved',
  4. rejected: 'Rejected'
  5. };
  6.  
  7. class Nancy {
  8. constructor(executor) {
  9. const tryCall = callback => Nancy.try(() => callback(this.value));
  10. const laterCalls = [];
  11. const callLater = getMember => callback => new Nancy(resolve => laterCalls.push(() => resolve(getMember()(callback))));
  12. const members = {
  13. [states.resolved]: {
  14. state: states.resolved,
  15. then: tryCall,
  16. catch: _ => this
  17. },
  18. [states.rejected]: {
  19. state: states.rejected,
  20. then: _ => this,
  21. catch: tryCall
  22. },
  23. [states.pending]: {
  24. state: states.pending,
  25. then: callLater(() => this.then),
  26. catch: callLater(() => this.catch)
  27. }
  28. };
  29. const changeState = state => Object.assign(this, members[state]);
  30. const apply = (value, state) => {
  31. this.value = value;
  32. changeState(state);
  33. for (const laterCall of laterCalls) {
  34. laterCall();
  35. }
  36. };
  37.  
  38. const getCallback = state => value => {
  39. if (this.state === states.pending) {
  40. if (value instanceof Nancy && state === states.resolved) {
  41. value.then(value => apply(value, states.resolved));
  42. value.catch(value => apply(value, states.rejected));
  43. } else {
  44. apply(value, state);
  45. }
  46. }
  47. };
  48.  
  49. const resolve = getCallback(states.resolved);
  50. const reject = getCallback(states.rejected);
  51. changeState(states.pending);
  52. try {
  53. executor(resolve, reject);
  54. } catch (error) {
  55. reject(error);
  56. }
  57. }
  58.  
  59. static resolve(value) {
  60. return new Nancy(resolve => resolve(value));
  61. }
  62.  
  63. static reject(value) {
  64. return new Nancy((_, reject) => reject(value));
  65. }
  66.  
  67. static try(callback) {
  68. return new Nancy(resolve => resolve(callback()));
  69. }
  70. }
Add Comment
Please, Sign In to add comment