2016-04-15 47 views
2

我在寫一個Mojolicious模塊/控制器,需要做兩個GET請求;一個接一個地。第二個GET請求取決於第一個響應數據。Mojolicious - 在同一個控制器中的兩個非阻塞GET請求

我希望這兩個請求都是非阻塞的。但是,我不能輕鬆地從第一個非阻塞回調的上下文中「返回」,爲第二個請求提供值。

sub my_controller { 

    my ($self) = @_; 

    $self->ua->get($first_endpoint, sub { 
     # handle response - extract value for second request? 
    }); 

    my $second_endpoint = 'parameter not available here'; 

    $self->ua->get($second_endpoint, sub {}); 

} 

如果可能,我不希望將第二個請求嵌套到第一個回調中?

+1

如果第二個依賴於第一個,並且在第一個失敗時不會完成,則嵌套正是您需要執行的操作。 – simbabque

+0

嵌套是指在處理非阻塞調用時如何指定兩個操作的順序,爲什麼要避免它? – polettix

回答

1

首先需要在控制器中調用render_later方法,因爲您編寫的是非阻塞代碼。

存在2種方式如何傳遞數據:

1)

sub action_in_controller { 
    my $c = shift->render_later; 

    $c->delay(
    sub { 
     my $delay = shift; 

     $c->ua->get('http://one.com' => $delay->begin); 
    }, 
    sub { 
     my ($delay, $tx) = @_; 

     $c->ua->post('http://second.com' => $delay->begin); 
    }, 
    sub { 
     my ($delay, $tx) = @_; 

     $c->render(text => 'la-la-la'); 
    } 
); 
} 

2)

sub action_in_controller { 
    my $c = shift->render_later; 

    $c->ua->get('http://one.com' => sub { 
    my ($ua, $tx) = @_; 

    $c->ua->post('http://second.com' => sub { 
     my ($ua, $tx) = @_; 

     $c->render(text => 'la-la-la'); 
    }); 
    }); 
} 

UPD

實測值使用科羅主叫的另一變型。 但是在perl 5.22中不起作用,需要應用patch來修復它。 你需要另外編寫插件Coro。例如 Here。您只需要ua.pl和插件Mojolicious::Plugin::Core