User Tools

Site Tools


Perl Mojo promises

promise.pl
#!/usr/bin/env perl
 
use v5.10;
use Mojo::Promise;
use Mojo::UserAgent;
 
# Wrap continuation-passing style APIs with promises
my $ua = Mojo::UserAgent->new;
 
sub get {
    my $promise = Mojo::Promise->new;
    $ua->get(@_ => sub {
                    my ($ua, $tx) = @_;
                    my $err = $tx->error;
                    $promise->resolve($tx) if !$err || $err->{code};
                    $promise->reject($err->{message});
                });
                return $promise;
}
 
# Perform non-blocking operations sequentially
get('https://mojolicious.org')
    ->then(sub {
            my $mojo = shift;
            say "MOJO1 ".$mojo->res->code;
            return get('https://metacpan.org');
    })
    ->then(sub {
        my $cpan = shift;
        say "CPAN1 ".$cpan->res->code;
    })
    ->catch(sub {
        my $err = shift;
        warn "Something went wrong: $err";
    })->wait;
 
 
# Synchronize non-blocking operations (all)
my $mojo = get('https://mojolicious.org');
my $cpan = get('https://metacpan.org');
 
 
Mojo::Promise->all($mojo, $cpan)
    ->then(sub {
        my ($mojo, $cpan) = @_;
        say "Mojo2 " . $mojo->[0]->res->code;
        say "CPAN2 " . $cpan->[0]->res->code;
    })
    ->catch(sub {
            my $err = shift;
            warn "Something went wrong: $err";
    })
    ->wait;
 
# Synchronize non-blocking operations (race)
my $mojo = get('https://mojolicious.org');
my $cpan = get('https://metacpan.org');
 
 
Mojo::Promise
    ->race($mojo, $cpan)
    ->then(sub {
            my $tx = shift;
            say $tx->req->url, ' won!';
    })
    ->catch(sub {
            my $err = shift;
            warn "Something went wrong: $err";
    })
    ->wait;
 
#EOF

Output

# ./promise.pl
MOJO1 200
CPAN1 200
Mojo2 200
CPAN2 200
https://metacpan.org won!