- 论坛徽章:
- 0
|
无意在google groups看到的帖子,提到了mojo::useragent的作用域问题,十分惊讶,实验以下代码,发现delay的第二个匿名子过程的get,都没有正确执行!- use 5.10.0;
- #!/usr/bin/env perl
- use strict;
- use warnings;
- use feature 'say';
- use Mojolicious::Lite;
- use Mojo::UserAgent;
- use Mojo::IOLoop;
- use Mojo::URL;
- get '/test' => sub {
- my $self = shift;
- my @data;
- my $url = Mojo::URL->new('http://www.baidu.com/s');
- [color=Red]my $ua = Mojo::UserAgent->new;[/color]
- my $result = [];
- Mojo::IOLoop->delay(
- sub {
- my $delay = shift;
- print "1st step!\n";
- $ua->get($url->clone->query({wd => 'mojo'}) => $delay->begin);
- },
- sub {
- my ($delay, @res) = @_;
- print "2nd step! with args: @{[ scalar @res ]}\n";
- foreach my $tx (@res) {
- if ($tx->success) {
- my $url = $tx->req->url->to_string;
- push @$result, "get $url success!\n";
- }
- }
- $ua->get($url->clone->query({wd => 'perl'}) => $delay->begin);
- },
- sub {
- my ($delay, @res) = @_;
- print "3rd step! with args: @{[ scalar @res ]}\n";
- foreach my $tx (@res) {
- if ($tx->success) {
- my $url = $tx->req->url->to_string;
- push @$result, "get $url success!\n";
- }
- }
- $self->render_text("all jobs done!\n@$result");
- }
- );
- };
- app->start;
复制代码 帖子也给出了解决方案,十分简单,将上面红色的代码,修改为:- state $ua = Mojo::UserAgent->new;
复制代码 代码上看$ua,作为closure context的变量,下面所有的匿名子过程,都应该能偶正确访问。而且这些匿名子过程也没有去修改$ua,那么为什么第二个匿名子过程,不能正确访问my声明的$ua呢?
增加了mojo的debug开关,看了下,第二个匿名子过程,如果访问的是my $ua,则只有request发送,之后get的callback不会执行!由此证明,第二个匿名sub,还是能访问$ua的,那为啥callback被忽略了?更迷惑了……
|
|