Skip to content

Commit

Permalink
promises can be settled with another promise
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Jan 31, 2018
1 parent dde6b9e commit 53615cb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
3 changes: 2 additions & 1 deletion Changes
@@ -1,5 +1,6 @@

7.62 2018-01-15
7.62 2018-02-01
- Fixed a promise resolution bug in Mojo::Promise.

7.61 2018-01-08
- Increased default upgrade_timeout from 60 to 180 seconds in
Expand Down
11 changes: 7 additions & 4 deletions lib/Mojo/Promise.pm
Expand Up @@ -109,7 +109,13 @@ sub _finally {

sub _settle {
my ($self, $status) = (shift, shift);

$_[0]->then(sub { $self->resolve(@_); () }, sub { $self->reject(@_); () })
and return $self
if blessed $_[0] && $_[0]->can('then');

return $self if $self->{result};

@{$self}{qw(result status)} = ([@_], $status);
$self->_defer;
return $self;
Expand All @@ -122,11 +128,8 @@ sub _then {

my @res;
return $new->reject($@) unless eval { @res = $cb->(@result); 1 };
return $new->resolve(@res);

return $new->resolve(@res)
unless @res == 1 && blessed $res[0] && $res[0]->can('then');

$res[0]->then(sub { $new->resolve(@_); () }, sub { $new->reject(@_); () });
}

1;
Expand Down
17 changes: 17 additions & 0 deletions t/mojo/promise.t
Expand Up @@ -185,4 +185,21 @@ Mojo::IOLoop->one_tick;
is_deeply \@results, [], 'promises not resolved';
is_deeply \@errors, ['third'], 'promise rejected';

# Settle with promise
$promise = Mojo::Promise->new->resolve('works');
@results = ();
$promise2 = Mojo::Promise->new->resolve($promise)
->then(sub { push @results, 'first', @_; @_ });
$promise2->then(sub { push @results, 'second', @_ });
Mojo::IOLoop->one_tick;
is_deeply \@results, ['first', 'works', 'second', 'works'], 'promises resolved';
$promise = Mojo::Promise->new->reject('works too');
@errors = ();
$promise2 = Mojo::Promise->new->reject($promise)
->catch(sub { push @errors, 'first', @_; @_ });
$promise2->then(sub { push @errors, 'second', @_ });
Mojo::IOLoop->one_tick;
is_deeply \@errors, ['first', 'works too', 'second', 'works too'],
'promises rejected';

done_testing();

0 comments on commit 53615cb

Please sign in to comment.