Advertisement
Guest User

Promise

a guest
May 1st, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use v6;
  2. use Test;
  3.  
  4. class Promise {
  5.     enum STATE <PENDING FULFILLED REJECTED>;
  6.  
  7.     has STATE $.state = STATE::PENDING;
  8.     has %!do-actions;
  9.     has $!reject-reason;
  10.     has $!fulfill-value;
  11.  
  12.     method fulfill($val!) {
  13.         if $!state != STATE::FULFILLED {
  14.             $!state = STATE::FULFILLED;
  15.             $!fulfill-value = $val;
  16.             for %!do-actions<fulfill>[] -> $f {
  17.                 $f($!fulfill-value);
  18.             }
  19.         }
  20.     }
  21.     method reject($reason!) {
  22.         if $!state != STATE::REJECTED {
  23.             $!state = STATE::REJECTED;
  24.             $!reject-reason = $reason;
  25.             for %!do-actions<reject>[] -> $r {
  26.                 $r[0]($!reject-reason);
  27.             }
  28.         }
  29.     }
  30.  
  31.     method then(&on-fulfill, &on-reject?) {
  32.         if $!state == STATE::PENDING {
  33.             %!do-actions<fulfill>.push: { &on-fulfill } if &on-fulfill;
  34.             %!do-actions<reject>.push: { &on-reject } if &on-reject;
  35.         } elsif $!state == STATE::REJECTED {
  36.             %!do-actions<reject>.map: { &on-reject($!reject-reason) };
  37.         } else {
  38.             %!do-actions<fulfill>.map: { &on-fulfill($!fulfill-value) };
  39.         }
  40.         return self;
  41.     }
  42. }
  43.  
  44. {
  45.     my $promise = Promise.new;
  46.  
  47.     my $value = 0;
  48.     $promise.then(sub ($arg) { $value = $arg });
  49.     ok !$value, "Hasn't been fulfilled yet";
  50.  
  51.     $promise.fulfill("OH HAI");
  52.  
  53.     is $promise.state, Promise::STATE::FULFILLED, "Correct state";
  54.     is $value, "OH HAI", "Code has been run";
  55. }
  56.  
  57. {
  58.     my $promise = Promise.new(state => Promise::STATE::FULFILLED,
  59.     value => "yay!");
  60.     is $promise.state, Promise::STATE::FULFILLED, "Already correct state";
  61.  
  62.     my $value = 0;
  63.     $promise.then(sub ($arg) { $value = $arg });
  64.  
  65.     is $value, "yay!", "Code ran immediately";
  66. }
  67.  
  68. {
  69.     my $promise = Promise.new;
  70.  
  71.     my $value = 0;
  72.     my $reason = 0;
  73.     $promise.then(sub ($arg) { $value  = $arg },
  74.     sub ($arg) { $reason = $arg });
  75.     ok !$reason, "Hasn't been rejected yet";
  76.  
  77.     $promise.reject("OH NOES");
  78.  
  79.     is $promise.state, Promise::STATE::REJECTED, "Correct state";
  80.     ok !$value, "Fulfill code didn't run";
  81.     is $reason, "OH NOES", "Reject code has been run";
  82. }
  83.  
  84. done;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement