The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Mojo::Pua - HTTP Client + Evo::Promise

VERSION

version 0.010

SYNOPSIS

Mojo::Pua inherits all methods from Mojo::UserAgent but returns Evo::Promise::Mojo object for each request

  use Evo 'Mojo::Pua';
  my $ua = Mojo::Pua->new();

  $ua->get("http://alexbyk.com/")

    ->then(sub($tx) {
      my $res = $tx->success;
      $res ? say $res->dom->at('title') : say "ERROR: ", $tx->error->{message};
    })

    ->catch(sub($err) { say "CATCHED: $err" })

    ->finally(sub { Mojo::IOLoop->stop; });

  Mojo::IOLoop->start;

Pay attention, 400 and 500 codes don't cause an exception. You should check Mojo::Transaction::HTTP/success to determine a success of a request.

A promise will be rejected on network errors only:

  $ua->get("http://localhost:2222/")

    ->catch(sub($err) { say "CATCHED: $err" })
    ->finally(sub     { Mojo::IOLoop->stop; });

But if you want to make life easier, see "want_code" promise onFulfill generator

DESCRIPTION

This module is based on Mojo::UserAgent and allows you to use promises (Evo::Promise::Mojo)

METHODS

All methods get, post ... from Mojo::UserAgent return a promise

FUNCTIONS

PUA

A single instance of Mojo::Pua.

  use Evo 'Mojo::Pua PUA';
  PUA->get('http://mail.ru')->then(sub {...});

want_code

Return a promise onFulfill handler that will be fulfilled only if the response code matches a given one. Then it will pass a Mojo::Message::Response object (not a transaction), or will throw an exception

  use Evo 'Mojo::Pua want_code';
  my $ua = Mojo::Pua->new();

  # accept only 200 code
  $ua->get("http://httpstat.us/200")->then(want_code 200)

    # pay attention, $res, not $tx
    ->then(sub ($res) { say $res->body })->finally(sub { Mojo::IOLoop->stop; });

  Mojo::IOLoop->start;

  # accept only 201 code
  $ua->get("http://httpstat.us/200")->then(want_code 201)

    # 201 != 200, promise is rejected
    ->catch(sub($err) { say "CATCHED: $err" })
    ->finally(sub     { Mojo::IOLoop->stop; });

  Mojo::IOLoop->start;

Return

SEE ALSO

Mojo::UserAgent Evo::Promise::Mojo https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

AUTHOR

alexbyk <alexbyk.com>

COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by alexbyk.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.