Meettya
Meettya

Reputation: 41

How assign MojoX::Redis result to variable?

I try to work with MojoX::Redis and I can`t understand how catch result in a variable.

In docs used "print"

 $redis->get(key => sub {
      my ($redis, $res) = @_;

      print "Value of ' key ' is $res->[0]\n";
  })

It worked, but useless. How I can assign result to a variable in "main" program?

PS. Indeed I really don`t understand asynchronous paradigm on this part.

Upvotes: 2

Views: 347

Answers (2)

Meettya
Meettya

Reputation: 41

I consult with author and he give me next solution :

my $data_out;

my $redis = $redis->ioloop(Mojo::IOLoop->new);

$redis->get( $user_query => sub {
      my ($redis, $res) = @_;

      $data_out = $res->[0];
      $redis->stop;
  });

 $redis->start;

 $self->render( text => "|$data_out|" );

full text in gist

I suppose without new ioloop Redis is "sited" on Mojolicious loop and receive data at the end only.

Upvotes: 2

bvr
bvr

Reputation: 9697

The sub is called when requested data arrives. You can close anonymous sub around variable from the outside to get it assigned.

my $result;

$redis->get(key => sub {
    my ($redis, $res) = @_;
    $result = $res->[0];
});

But pay attention to that variable is filled asynchronously, so it will not be immediately available. Probably best approach is to process result within the anonymous sub.

Upvotes: 2

Related Questions