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

NAME

Data::Promise - simple promise like interface

SYNOPSIS

  use Modern::Perl;
  use Data::Promose;

  my $p=new Data::Promise(cb=>sub {
    my ($resolve,$reject)=@_;

    if(...) {
      # pass context
      $resolve->('ok');
    } else {
      $reject->('something went wrong');
    }
  });

  sub pass_function { ... }
  sub fail_function { ... }
  $p->then(\&pass_function,\&fail_function);


  # delayed example
  my $p=new Data::Promise(
    delayed=>1,
    cb=>sub {

    if(...) {
      # pass context
      $resolve->('ok');
    } else {
      $reject->('something went wrong');
    }
  });

  $p->then(\&pass_function,\&fail_function);
  # pass and fail functions will not be called until now
  $p->do_resolve;

  ## create a rejected promise
  my $p=Data::Promise->reject(42);

  # you can be sure your fail funtion will be called
  $p->then(\&pass_function,\&fail_function);

  ## create a resolved promise
  my $p=Data::Promise->resolve(42);

  # you can be sure your pass funtion will be called
  $p->then(\&pass_function,\&fail_function);

DESCRIPTION

A light and simple Promise object based on the current es6 implementation. This promise object class was written to mimic how promise(s) are implemnted in the wild. This may or may not be the class you are looking for.

OO Constructor Arguments

  • cb=>sub { my ($resovle,$reject)=@_ }

    The callback function used to resolve the object. If no function is passed in then the object will never resolve!

  • delayed=>0|1

    This enables or disables manual control over when your cb function will be called. The default is false.

Promise functions

if($p->pending) { ... }

Used as a state checking interface, this method returns true if the promise is still being resolved, false if it is not.

my $p=$p->then(\&resolve,\&reject)

This method provides a way to attach functions that will be called when the object is either rejected or resovled.

my $p=$p->catch(\&reject)

This is really a wrapper function for: $p->then(undef,\&reject);

my $p=Data::Promise->reject(@args)

Creates a rejected promise with @args as the rejected data.

my $p=Data::Promise->resolve(@args)

Creates a resolved promise with @args as the resolved data.

my $p=$p->finally(sub {});

Allows the addition of functions that will be called once the object is resolved. The functions will recive no arguments, and are called reguardless of the resolved or rejected state.

my $p=$p->do_resolve

When the promise is constructed in a delayed state, this method must be called to activate the cb method.

AUTHOR

Michael Shipper <AKALINUX@CPAN.ORG>