2015. 3. 8.

using event loop for aync funtion

use v5.12;
use AnyEvent;
use Search::Elasticsearch::Async;

# EV must be installed
use Promises (backend => ['EV'], 'deferred');

my $cv = AnyEvent->condvar;

my $e = Search::Elasticsearch::Async->new(

nodes=>'http://localhost:9200'
);


my $doc_size =1000;
my $success_count = 0;

my $bulk = $e->bulk_helper(
index=>'my_app',
type=>'blog_post',
on_success => sub {
#say "success";

},
on_error => sub{
say "fail";
}
);


my @arr_res =();


sub main_loop{


my $idx =0;
@arr_res = ();
for (1..$doc_size)
{
push (@arr_res, '{"a": 1111, "b":222, "name":"KKKKKK"}');

}
$bulk->create_docs(@arr_res)->then (
sub {
say "bulk ok";


}, ##success
sub {
say "bulk fail";
} #fail.
);
$bulk->flush();

}

sub start_ {
my $d = deferred;

    my $w;
    $w = AnyEvent->io(
        fh   => \*STDIN,
        poll => 'r',
        cb   => sub {
            chomp( my $input = );
            undef $w;
            # resolve the promise
            $d->resolve($input);
        }
    );

    # return a promise
    return $d->promise;
}


sub main {

start_()
->then( \&main_loop)
->then(sub { print "fin.\n"; })
->catch( sub { print "errors";})
->finally( \&main );

}


main();
EV::run;


댓글 없음:

댓글 쓰기