[Moscow.pm] Coro

. akovbovich gmail.com
3 11:39:51 PST 2012


   ?

    https://metacpan.org/module/Combinator

When you are tired of writing layered closures

use AnyEvent::DBI;
...
$dbh->exec("select ...", sub {
    ...
    $dbh->exec("select ...", sub {
        ...
        $dbh->exec("select ...", sub {
            ...
            $dbh->exec("select ...", sub {
                ...
            });
        });
    });
});

You can achieve that like this:

use Combinator;
use AnyEvent::DBI;
...
{{com
    $dbh->exec("select ...", {{next}});
    ...
  --ser
    $dbh->exec("select ...", {{next}});
    ...
  --ser
    $dbh->exec("select ...", {{next}});
    ...
  --ser
    $dbh->exec("select ...", {{next}});
    ...
}}com

27  2012. 10:05  Dmitry Karasik
<dmitry  karasik.eu.org> :
> On Fri, Jan 27, 2012 at 12:46:42AM +0200, Alexandr Gomoliako wrote:
>> >    .  AE      
>> >   ,   ,   (.. 
>> > ) ?
>>
>> AE   ,     .
>
>        -   .       -  
>  ,   ,          .
>
>>    ,    .   
>>         :
>
>          ;)
>
>>
>> sub request {
>>   my ($host, $port, $buf, $cb) = @_;
>>   my ($fh, $w, $t, $callback);
>>
>>   $callback = sub {
>>     &$cb;
>>     undef $t;
>>     undef $w;
>>   };
>>
>>   tcp_connect $host, $port, sub {
>>     ($fh) = @_;
>>
>>     # writable
>>     $t = AE::timer 5, 0, $callback;
>>     $w = AE::io $fh, 1, sub {
>>
>>       my $len = syswrite $fh, $buf, ...;
>>
>>       # readable
>>       $t = AE::timer 5, 0, $callback;
>>       $w = AE::io $fh, 0, sub {
>>
>>         my $len = sysread $fh, $buf, ...;
>>
>>         &$callback($buf);
>>       };
>>     };
>>   };
>> }
>>
>> sub do_some {
>>   my ($arg, $cb) = @_;
>>
>>   request '1.2.3.4', 123, "foo, $arg", sub {
>>     my ($foo) = @_;
>>
>>     request '2.3.4.5', 123, "bar, $foo", sub {
>>       my ($bar) = @_;
>>
>>       &$cb($foo, $bar);
>>     };
>>   };
>> }
>>
>> sub do_many {
>>   my ($arg, $cb) = @_;
>>   my (@res, $cnt);
>>
>>   my $gather = sub {
>>     push @res, \@_;
>>     &$cb(@res) if --$cnt == 0;
>>   };
>>
>>   $cnt++;
>>   request '1.2.3.4', 123, "foo, $arg", $gather;
>>
>>   $cnt++;
>>   request '1.2.3.4', 123, "foo, $arg", $gather;
>>
>>   $cnt++;
>>   request '1.2.3.4', 123, "foo, $arg", $gather;
>> }
>>
>>
>> do_some "foobar", sub {
>>   print "got @_\n";
>>
>>   do_many "baz", sub {
>>     print "got many @_\n";
>>   };
>> };
>> --
>> Moscow.pm mailing list
>> moscow-pm  pm.org | http://moscow.pm.org
>
> --
> Sincerely,
>    Dmitry Karasik
>
> --
> Moscow.pm mailing list
> moscow-pm  pm.org | http://moscow.pm.org


Moscow-pm