Guest User

Promises

a guest
May 1st, 2013
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 0.78 KB | None | 0 0
  1. use v6;
  2.  
  3. class Promise {
  4.     enum STATE <PENDING FULFILLED REJECTED>;
  5.  
  6.     has STATE $!state;
  7.     has %!do-actions;
  8.  
  9.     method state {
  10.         $!state;
  11.     }
  12.    
  13.     method fulfill($val!) {
  14.         if $!state != STATE::FULFILLED {
  15.             $!state = STATE::FULFILLED;
  16.             %!do-actions<fulfill> = $val;
  17.         }
  18.     }
  19.     method reject($reason!) {
  20.         if $!state != STATE::REJECTED {
  21.             $!state = STATE::REJECTED;
  22.             %!do-actions<reject> = $reason;
  23.         }
  24.     }
  25.  
  26.     method then($on-fulfill?, $on-reject?) {
  27.         if $!state == STATE::PENDING {
  28.             %!do-actions<fulfill>.push: { $on-fulfill } if $on-fulfill;
  29.             %!do-actions<reject>.push: { $on-reject } if $on-reject;
  30.         } elsif %!state == STATE::REJECTED {
  31.             %!do-actions<reject>.map: { $^x.() };
  32.         } else {
  33.             %!do-actions<fulfill>.map: { $^x.() };
  34.         }
  35.         return self;
  36.     }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment