假设我想取消一个正在运行的请求 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 passedMojo::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/