Mojo-Promise-Role-Get

Wait for the results of a Mojo::Promise


License
Artistic-2.0

Documentation

NAME

Mojo::Promise::Role::Get - Wait for the results of a Mojo::Promise

SYNOPSIS

use Mojo::IOLoop;
use Mojo::Promise;
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;

# long way of writing $ua->get('http://example.com')->result
my $res = $ua->get_p('http://example.com')->with_roles('+Get')->get->result;

# wait for multiple requests at once
my @responses = map { $_->[0]->result } Mojo::Promise->all(
  $ua->get_p('http://example.com'),
  $ua->get_p('https://www.google.com'),
)->with_roles('Mojo::Promise::Role::Get')->get;

# request with exception on timeout
my $timeout = Mojo::Promise->new;
Mojo::IOLoop->timer(1 => sub { $timeout->reject('Timed out!') });
my $res = Mojo::Promise->race($ua->get_p('http://example.com'), $timeout)
  ->with_roles('Mojo::Promise::Role::Get')->get->result;

DESCRIPTION

Mojo::Promise::Role::Get is a Mojo::Promise role that adds a "get" method to facilitate the usage of asynchronous code in a synchronous manner, similar to "get" in Future.

Note: Like in Future, "get" cannot retrieve results when the event loop is already running, as that can recurse into the event reactor. Unlike in Future, this is true even if the promise has already been resolved or rejected, because retrieving Mojo::Promise results always requires running the event loop.

METHODS

Mojo::Promise::Role::Get composes the following methods.

get

my @results = $promise->get;
my $first_result = $promise->get;

Blocks until the promise resolves or is rejected. If it is fulfilled, the results are returned. In scalar context the first value is returned. If the promise is rejected, the (first value of the) rejection reason is thrown as an exception.

An exception is thrown if the "ioloop" in Mojo::Promise is running, to prevent recursing into the event reactor.

BUGS

Report any issues on the public bugtracker.

AUTHOR

Dan Book <dbook@cpan.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2018 by Dan Book.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)

SEE ALSO

Future