Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use v6;
- use Test;
- class Promise {
- enum STATE <PENDING FULFILLED REJECTED>;
- has STATE $.state = STATE::PENDING;
- has %!do-actions;
- has $!reject-reason;
- has $!fulfill-value;
- method fulfill($val!) {
- if $!state != STATE::FULFILLED {
- $!state = STATE::FULFILLED;
- $!fulfill-value = $val;
- for %!do-actions<fulfill>[] -> $f {
- $f($!fulfill-value);
- }
- }
- }
- method reject($reason!) {
- if $!state != STATE::REJECTED {
- $!state = STATE::REJECTED;
- $!reject-reason = $reason;
- for %!do-actions<reject>[] -> $r {
- $r[0]($!reject-reason);
- }
- }
- }
- method then(&on-fulfill, &on-reject?) {
- if $!state == STATE::PENDING {
- %!do-actions<fulfill>.push: { &on-fulfill } if &on-fulfill;
- %!do-actions<reject>.push: { &on-reject } if &on-reject;
- } elsif $!state == STATE::REJECTED {
- %!do-actions<reject>.map: { &on-reject($!reject-reason) };
- } else {
- %!do-actions<fulfill>.map: { &on-fulfill($!fulfill-value) };
- }
- return self;
- }
- }
- {
- my $promise = Promise.new;
- my $value = 0;
- $promise.then(sub ($arg) { $value = $arg });
- ok !$value, "Hasn't been fulfilled yet";
- $promise.fulfill("OH HAI");
- is $promise.state, Promise::STATE::FULFILLED, "Correct state";
- is $value, "OH HAI", "Code has been run";
- }
- {
- my $promise = Promise.new(state => Promise::STATE::FULFILLED,
- value => "yay!");
- is $promise.state, Promise::STATE::FULFILLED, "Already correct state";
- my $value = 0;
- $promise.then(sub ($arg) { $value = $arg });
- is $value, "yay!", "Code ran immediately";
- }
- {
- my $promise = Promise.new;
- my $value = 0;
- my $reason = 0;
- $promise.then(sub ($arg) { $value = $arg },
- sub ($arg) { $reason = $arg });
- ok !$reason, "Hasn't been rejected yet";
- $promise.reject("OH NOES");
- is $promise.state, Promise::STATE::REJECTED, "Correct state";
- ok !$value, "Fulfill code didn't run";
- is $reason, "OH NOES", "Reject code has been run";
- }
- done;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement