Last active
December 16, 2015 20:59
-
-
Save tadzik/5496732 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Test::More tests => 12; | |
package Promise { | |
use Moo; | |
has state => (is => 'ro', default => sub { 'PENDING' }); | |
has on_fulfill => (is => 'ro', default => sub { [] }); | |
has on_reject => (is => 'ro', default => sub { [] }); | |
has value => (is => 'ro'); | |
has reason => (is => 'ro'); | |
sub fulfill { | |
my ($self, $value) = @_; | |
return unless $self->state eq 'PENDING'; | |
$self->{state} = 'FULFILLED'; | |
for (@{$self->on_fulfill}) { | |
$_->($value) | |
} | |
} | |
sub reject { | |
my ($self, $value) = @_; | |
return unless $self->state eq 'PENDING'; | |
$self->{state} = 'REJECTED'; | |
for (@{$self->on_reject}) { | |
$_->($value) | |
} | |
} | |
sub then { | |
my ($self, $yep, $nope) = @_; | |
push @{$self->on_fulfill}, $yep; | |
push @{$self->on_reject}, $nope if $nope; | |
if ($self->state eq 'FULFILLED') { | |
$yep->($self->value) | |
} elsif ($self->state eq 'REJECTED') { | |
$nope->($self->reason) | |
} | |
return $self | |
} | |
} | |
{ | |
my $promise = Promise->new; | |
my $value = 0; | |
$promise->then(sub { $value = shift }); | |
ok !$value, "Hasn't been fulfilled yet"; | |
$promise->fulfill("OH HAI"); | |
is $promise->state, "FULFILLED", "Correct state"; | |
is $value, "OH HAI", "Code has been run"; | |
} | |
{ | |
my $promise = Promise->new(state => "FULFILLED", value => "yay!"); | |
is $promise->state, "FULFILLED", "Already correct state"; | |
my $value = 0; | |
$promise->then(sub { $value = shift }); | |
is $value, "yay!", "Code ran immediately"; | |
} | |
{ | |
my $promise = Promise->new; | |
my $value = 0; | |
my $reason = 0; | |
$promise->then(sub { $value = shift }, sub { $reason = shift }); | |
ok !$reason, "Hasn't been rejected yet"; | |
$promise->reject("OH NOES"); | |
is $promise->state, "REJECTED", "Correct state"; | |
ok !$value, "Fulfill code didn't run"; | |
is $reason, "OH NOES", "Reject code has been run"; | |
} | |
{ | |
my $promise = Promise->new; | |
my $value = 0; | |
$promise->then(sub { $value++ }); | |
$promise->then(sub { $value++ }); | |
$promise->then(sub { $value++ }); | |
ok !$value, "Hasn't been fulfilled yet"; | |
$promise->fulfill("OH HAI"); | |
is $promise->state, "FULFILLED", "Correct state"; | |
is $value, 3, "Code has been run"; | |
} | |
done; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment