I have done it with closure. Sure, I tried it at the first and it did not work, so I started searching for an alternative (this is how I came to the approach in the OP).
The problem is with the for() loops. I cannot use in the subprocess any var, crated within the loop for() even $_).
I am not sure I understand - why :)
What was the remedy:
my @looper = (0..5);
foreach my $lp (@looper){
... subprocess preparation as in the OP ...
sub {
my $i = $lp || 5;
return $i;
}
}
Now it shows every number from the @looper.
The complete working example:
use Mojo::Base -strict, -signatures, -async_await;
use Mojo::IOLoop::Subprocess;
use Mojo::Promise;
async sub testMehod{
$c->render_later;
my $start_timer1 = Time::HiRes::gettimeofday();
show "BEFORE";
my @promises;
my @looper = (0..5);
foreach my $lp (@looper){
say "(START) This is $lp loop";
my $subprocess = Mojo::IOLoop::Subprocess->new;
push @promises, $subprocess->run_p(
sub {
my $i = $lp || 5;
my $sp = shift; # $subprocess
#my $i = shift || 3;
#my $promise = Mojo::Promise->new;
say "Hello, from $i and $$!";
sleep 2;
say "Good bye, from $i and $$!";
#$promise->resolve("Done for $i");
#return $promise;
return "Done for $i";
#}->($_)
}
)->then(sub ($_result) {
show $_result;
return $_result;
})->catch(sub {
my $err = shift;
say "Subprocess error: $err";
});
$subprocess->ioloop->start unless $subprocess->ioloop->is_runn
+ing;
say "(END) This is $lp loop";
}
my @results = await Mojo::Promise->all_settled(@promises);
show @results;
my $stop_timer1 = Time::HiRes::gettimeofday();
my $total1 = sprintf("%.5f\n", $stop_timer1 - $start_timer1);
return $c->render(text => "All done. Parallel: within $total1", st
+atus => 405);
}
If you know - why it did not work with for() loop - please, kindly, share this knowledge :)
Thank you!