Async-Methods
view release on metacpan or search on metacpan
NAME
Async::Methods - Namespaced sugar methods for async/await and
future/promise based code
SYNOPSIS
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
# Normal synchronous code
print $ua->get('http://trout.me.uk/')->result->body;
# Equivalent code running synchronously atop promises
print $ua->get_p('http://trout.me.uk')->then::result->await::body;
# Equivalent code within an async subroutine
use Mojo::Base -async_await, -signatures;
async sub fetch ($url) {
await $ua->get_p($url)->then::result->then::body;
}
print fetch($url)->await::this;
DESCRIPTION
Async::Methods provides a set of helper methods operating via namespace
that make chaining together asynchronous methods easier. This is not at
all meant to be a replacement for the "async" and "await" keywords
available via Future::AsyncAwait or the "-async_await" flag to
Mojo::Base and in fact is largely meant to be used *with* such
facilities.
Note that in the following code I use $p for example variables but they
can be Future or Mojo::Promise objects or (hopefully) objects of any
other class that provides a similar interface.
Note that methods of each type provided can be called three ways:
$obj->the_type::some_method(@args);
will call "some_method" on a relevant object, and is effectively simply
sugar for the second type,
$obj->the_type::_(some_method => @args);
which calls the method name given in its first argument (yes, this means
that you can't use the first syntax to call a method called "_" but the
author of this module strongly suspects that won't be an inconvience in
most cases).
Thirdly, to match perl's capacity to allow <$obj->$cb(@args)> as a
syntax, you can also call:
$obj->the_type::_(sub { ... } => @args);
$obj->the_type::_($cb => @args);
to call that code reference as a method.
METHODS
start::
my $p = $obj->start::some_method(@args);
my $p = $obj->start::_(some_method => @args);
my $p = $obj->start::_(sub { ... } => @args);
"start::" methods don't do anything special in and of themselves but
register the $obj with Async::Methods to allow "catch::" and "else::" to
work correctly (see their documentation below for why you might find
that useful). Other than the registration part, this is entirely
equivalent to
my $p = $obj->some_method(@args);
then::
my $then_p = $p->then::some_method(@args);
my $then_p = $p->then::_(some_method => @args);
my $then_p = $p->then::_(sub { ... } => @args);
"then::" allows for chaining an additional method call from the return
value of the previous promise (assuming it's successful). As such, on
its own this is equivalent to
my $then_p = $p->then(
sub ($obj, @rest) { $obj->some_method(@args, @rest)) }
);
Note that "then::" does not require anything special of the promise upon
which it's called to provide the base functionality, but *does* need to
( run in 0.614 second using v1.01-cache-2.11-cpan-df04353d9ac )