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

标签 perl promise user-agent mojolicious

假设我想取消一个正在运行的请求 Mojo::UserAgent ?我该怎么做?

最佳答案

演示如何取消 promise

在此示例中,我们创建了一个随机 Timer promise 和一个 HTTP Get promise 。第一个获胜的rejects另一个 promise 。

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可能更适用。我们不必手动拒绝其他 promise ,但我想通过手动 reject 来抽象地演示拒绝。

关于perl - 如何取消来自 Mojo::UserAgent 的正在进行的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64494243/

相关文章:

perl - 如何使用 perl Image::Magick 剪切图像的透明部分?

mysql - 如何在 Perl 中设置要处理的消息?

perl - 为什么我的父进程在退出之前看不到子进程的输出?

javascript - `Promise.all` 和大量异步操作的性能考虑

linux - 如何安装 Perl 脚本的依赖项?

javascript - 将 Promise 函数映射到数组不会保留结果

javascript - 检测 iPhone 5 及其以下的任何 iOS 设备

PHP:浏览器版本号 user-agent with Version/x.x.x (Safari & Opera)

php - 如何将您的 PHP 脚本伪装成浏览器?

javascript - 使用 promise 时的逻辑流程