Created
February 8, 2017 22:34
-
-
Save aferreira/4568d226fcd45a39696cbd9e782de326 to your computer and use it in GitHub Desktop.
Read lines from a file non-blocking while doing non-blocking operations
This file contains hidden or 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 Mojo::Base -strict; | |
| use Mojo::IOLoop::LineReader; | |
| use Mojo::UserAgent; | |
| use Mojo::IOLoop; | |
| use Data::Dump 'pp'; | |
| use File::Temp qw(tempfile :seekable); | |
| sub run { | |
| # write DATA to temp file | |
| my $fh = tempfile; | |
| print {$fh} do { local $/; <DATA> }; | |
| $fh->seek( 0, SEEK_SET ); # rewind | |
| # Read lines from a file non-blocking while doing non-blocking operations | |
| my $r = Mojo::IOLoop::LineReader->new($fh); | |
| my $ua = Mojo::UserAgent->new; | |
| $r->on( | |
| readln => sub { | |
| my ( $r, $url ) = @_; | |
| say "READ"; | |
| chomp $url; | |
| $ua->get( | |
| $url => sub { | |
| my ( $ua, $tx ) = @_; | |
| say "GET"; | |
| pp( $tx->res->json->{release_count} ); | |
| } | |
| ); | |
| } | |
| ); | |
| $r->start; | |
| return $r; | |
| } | |
| my $r = run(); | |
| Mojo::IOLoop->start; | |
| __DATA__ | |
| https://fastapi.metacpan.org/v1/author/FERREIRA | |
| https://fastapi.metacpan.org/v1/author/GBARR | |
| https://fastapi.metacpan.org/v1/author/MIYAGAWA | |
| https://fastapi.metacpan.org/v1/author/INGY | |
| __END__ | |
| Output is below. | |
| Why all READ callbacks happen before GET callbacks? | |
| READ | |
| READ | |
| READ | |
| READ | |
| GET | |
| { "backpan-only" => 425, "cpan" => 1609, "latest" => 197 } | |
| GET | |
| { "backpan-only" => 275, "cpan" => 68, "latest" => 28 } | |
| GET | |
| { "backpan-only" => 85, "cpan" => 122, "latest" => 31 } | |
| GET | |
| { "backpan-only" => 102, "cpan" => 1572, "latest" => 199 } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment