Snippets

Brian Medley Initial future idea

Created by Brian Medley last modified Brian Medley
use Mojo::Base -strict;

use Mojo::IOLoop;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

my $future = $ua->aget('www.google.com' => {Accept => '*/*'});

my $title = sub {
    my ($future) = @_;

    say $future->tx->res->dom->at('title')->text;
    
    return $future;
};

$future->then($title)->then(sub { 
    my ($future) = @_;

    return $future->aget('http://slashdot.org', sub { say("Then, yes") });
})->then($title);

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
#!perl
 
use strict;
use warnings;
 
use Mojo::UserAgent;
use Mojo::IOLoop;

use Mojo::Base -strict;
 
{
    package Mojo::UserAgent::Promises; 
     
    use strict;
    use warnings;
 
    use Promises qw[ deferred ];
     
    use Mojo::Base 'Mojo::UserAgent';

    use Mojo::Util 'monkey_patch';
 
    sub start {
        my ($self, $tx, $cb) = @_;
        my $d = deferred;
        $self->SUPER::start( $tx, sub { $d->resolve( @_ ) });            
        return $d->then( $cb ) if $cb;
        return $d->promise;
    }

    for my $name (qw(DELETE GET HEAD OPTIONS PATCH POST PUT)) {
      monkey_patch __PACKAGE__, sprintf("a%s", lc($name)), sub {
        my $self = shift;

        my $method = lc($name);

        $self->$method(@_);
      };
    }
}

my $ua    = Mojo::UserAgent::Promises->new;
my $delay = Mojo::IOLoop->delay;
my @steps = ();
my @titles = ();
 
foreach my $url (qw[ mojolicio.us www.cpan.org ]) {
    push(@steps, sub {
        my $end = $delay->begin;

        $ua->aget($url)->then(
            sub {
                my ($promise, $tx) = @_;

                my $title = $tx->res->dom->at('title')->text;
                push(@titles, $title);

                $end->();
            }
        )->then(sub {
            say("Joy");
        });
    });
}
 
$delay->steps(@steps)->wait;
 
print join "\n" => @titles;
print "\n";
 
1;

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.