I tried to return a promise from a subroutine which contained some data obtained from a HTTP request to a web server. But I couldn't call then
on the result. Having narrowed it down, it doesn't seem possible to assign the promise returned from get_p
to a variable and then use it as a promise.
Here's an example. I would have thought that the two requests are exactly the same, but only the second one runs the code in the then block.
Can someone please explain what the difference is, and how I should return a promise from a subroutine if I want to chain more then
methods outside the sub?
#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use 5.024;
use Data::Dumper;
use Mojo::IOLoop;
use Mojo::UserAgent;
my $promise = Mojo::UserAgent->new->get_p('http://example.com');
$promise->then(sub {
my $tx = shift;
warn 'Using variable';
warn $tx->result->body;
})->wait;
Mojo::UserAgent->new->get_p('http://example.com')
->then(sub {
my $tx = shift;
warn 'Not using variable';
warn $tx->result->body;
})->wait;