Skip to content

Instantly share code, notes, and snippets.

@tadzik
Last active December 16, 2015 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tadzik/5496546 to your computer and use it in GitHub Desktop.
Save tadzik/5496546 to your computer and use it in GitHub Desktop.
use Test;
class Promise {
enum State <PENDING FULFILLED REJECTED>;
has State $.state = PENDING;
has @.on-fulfill;
has @.on-reject;
has $.value;
has $.reason;
method fulfill($value) {
return unless $!state == PENDING;
$!state = FULFILLED;
for @!on-fulfill -> &cb {
&cb($value)
}
}
method reject($reason) {
return unless $!state == PENDING;
$!state = REJECTED;
for @!on-reject -> &cb {
&cb($reason)
}
}
method then(&yep, &nope?) {
@!on-fulfill.push: &yep;
@!on-reject.push: &nope if &nope;
if $!state == FULFILLED {
&yep($!value)
} elsif $!state == REJECTED {
&nope($!reason)
}
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({ $value = $^arg });
is $value, "yay!", "Code ran immediately";
}
{
my $promise = Promise.new;
my $value = 0;
my $reason = 0;
$promise.then({ $value = $^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";
}
{
my $promise = Promise.new;
my $value = 0;
$promise.then({ $value++ });
$promise.then({ $value++ });
$promise.then({ $value++ });
ok !$value, "Hasn't been fulfilled yet";
$promise.fulfill("OH HAI");
is $promise.state, 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