【问题标题】:Mojolicious - two non-blocking GET requests in the same controllerMojolicious - 同一控制器中的两个非阻塞 GET 请求
【发布时间】:2016-04-15 14:17:02
【问题描述】:

我正在编写一个需要发出两个 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 {}); 

}

如果可能,我不希望将第二个请求嵌套到第一个回调中?

【问题讨论】:

  • 如果第二个依赖于第一个,如果第一个失败就不会做,嵌套正是你需要做的。
  • 嵌套是在处理非阻塞调用时指定两个操作的顺序,为什么要避免呢?

标签: perl mojolicious


【解决方案1】:

首先需要在控制器中调用render_later方法,因为您编写的是非阻塞代码。

存在两种传递数据的方式:

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

发现了另一种使用 Coro 调用的变体。 但是在 perl 5.22 中它不起作用,需要申请 patch 来修复它。 您还需要编写插件 Coro。 Here 示例。你只需要ua.pl 和插件Mojolicious::Plugin::Core

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多