如何取消来自 Mojo::UserAgent 的正在进行的请求?

How can I cancel in-flight requests from Mojo::UserAgent?

假设我想取消 Mojo::UserAgent 的飞行请求?我该怎么做?

演示如何取消承诺

在这个例子中,我们创建了一个随机的 Timer 承诺和一个 HTTP Get 承诺。第一个赢得 rejects 另一个承诺。

use Mojo::UserAgent;
use v5.30;
use experimental 'signatures';

my $ua = Mojo::UserAgent->new;
my $p1 = Mojo::Promise->timer(rand('0.4') , 'Timeout');
my $p2 = $ua->get_p('https://www.cpanel.net/is_hiring_message_evan_carroll_on_linkedin');

$p1
  ->then(sub ($res) {$p2->reject("\t> reject $p2"); say $res})
  ->catch(sub ($msg) {say $msg});
$p2
  ->then(sub ($res) {$p1->reject("\t> reject $p1"); say $res})
  ->catch(sub ($msg) {say $msg});

Mojo::Promise->new->all( $p1, $p2 )->catch(sub{})->wait;

请注意,如果超时成功,您可能会收到 Premature connection close 的错误事件,这正是您所期望的。你可以在这里看到'我们正在使用 Mojo::Promise's all,

Returns a new Mojo::Promise object that either fulfills when all of the passed Mojo::Promise objects have fulfilled or rejects as soon as one of them rejects. If the returned promise fulfills, it is fulfilled with the values from the fulfilled promises in the same order as the passed promises.

注意,在这种情况下 race 可能更适用。我们不必手动拒绝另一个承诺,但我想用 reject 手动在摘要中演示拒绝。

这实际上行不通。

考虑以下几点:

use Mojo::UserAgent;
use v5.26;
use experimental 'signatures';

my $ua = Mojo::UserAgent->new;
my $p1 = Mojo::Promise->timer(0.004, 'Timeout');
my $p2 = $ua->get_p('http://www.cpanel.net/is_hiring_message_evan_carroll_on_linkedin');

$p1
  ->then(sub ($res) {$p2->reject("\t> reject $p2"); say $res})
  ->catch(sub ($msg) {say $msg});
$p2
  ->then(sub ($res) {$p1->reject("\t> reject $p1"); say $res})
  ->catch(sub ($msg) {say $msg});

Mojo::Promise->new->all( $p1, $p2 )->catch(sub{})->wait;

Mojo::Promise->timer(2)->wait();

此处的更改是放弃 SSL,始终在 0.004 秒后超时,并让事件循环多等待 2 秒。

如果你跟踪上面的内容,你会看到请求继续。