PrePAN

Sign in to PrePAN

Mojo::Promise::Limitter limit outstanding calls to Mojo::Promise

Good

Synopsis

use Mojo::Promise::Limitter;
use Mojo::Promise;
use Mojo::IOLoop;

my $limitter = Mojo::Promise::Limitter->new(2);

my @job = 'a' .. 'e';

Mojo::Promise->all(
  map { my $name = $_; $limitter->limit(sub { job($name) }) } @job,
)->then(sub {
  my @result = @_;
  warn "\n";
  warn "results: ", (join ", ", map { $_->[0] } @result), "\n";
})->wait;

sub job {
  my $name = shift;
  my $text = "job $name";
  warn "started $text\n";
  return Mojo::Promise->new(sub {
    my $resolve = shift;
    Mojo::IOLoop->timer(0.1 => sub {
      warn "        $text finished\n";
      $resolve->($text);
    });
  });
}

Description

Motivation

I'm currently playing with async-await in Mojolicious. It's great.

When I want to call a lot of external commands, I noticed that there is no way to limit concurrent calls to external commands. So I tried creating Mojo::Promise::Limitter.

Questions

  • Is there already a module that has the same functionality as this module?
  • Any feedback (including implementation) is welcome.

Comments

Please sign up to post a review.