spawn subprocess with promise

This commit is contained in:
Denis Fedoseev 2018-08-01 10:11:43 +03:00
parent a774698d6e
commit 87ad4111a8

View file

@ -4,6 +4,8 @@ use warnings;
use lib 'lib';
use Mojolicious::Lite; # app, get, post is exported.
use Mojo::Promise;
use Mojo::IOLoop;
use File::Basename qw/basename fileparse/;
use File::Path 'mkpath';
@ -255,22 +257,12 @@ post '/upload' => ( authenticated => 1 ) => sub {
# Save to file
$image->move_to($image_file);
# Operation that would block the event loop for 5 seconds
my $subprocess = Mojo::IOLoop::Subprocess->new;
$subprocess->run(
sub {
my $subprocess = shift;
store_image($image_file, $image->filename, $user_id);
},
sub {
my ($subprocess, $err, @results) = @_;
say "Subprocess error: $err" and return if $err;
say "I $results[0] $results[1]!";
}
);
$log->debug("Spwan subprocess");
$subprocess->ioloop->start unless $subprocess->ioloop->is_running;
my $promise = store_image($image_file, $image->filename, $user_id);
Mojo::Promise->all($promise)->then(sub {
$self->render(
json => {
files => [
@ -283,6 +275,30 @@ post '/upload' => ( authenticated => 1 ) => sub {
]
}
);
})->wait;
# $log->debug("wait for promise");
# Mojo::Promise->all($spawn_subprocess)->then(sub {
# $self->render(
# json => {
# files => [
# {
# name => $image->filename,
# size => $image->size,
# url => sprintf( '/images/orig/%s', $filename ),
# thumbnailUrl => sprintf( '/images/200/%s', $filename ),
# }
# ]
# }
# );
# })->catch(sub {
# my $err = shift;
# warn "Something went wrong: $err";
# })->wait;
# Redirect to top page
# $self->redirect_to('index');
@ -310,6 +326,11 @@ sub store_image {
my $original_filename = shift;
my $user_id = shift;
my $promise = Mojo::Promise->new;
# Operation that would block the event loop for 5 seconds
Mojo::IOLoop->subprocess(
sub {
my $subprocess = shift;
my $filename = fileparse($image_file);
my $imager = Imager->new();
@ -350,7 +371,20 @@ sub store_image {
die sprintf('Can\'t save file %s', $filename);
}
$log->debug("done!");
return $filename;
},
sub {
my ($subprocess, $err, @results) = @_;
say "Subprocess error: $err" and return if $err;
$promise->reject("I $results[0] $results[1]!") if $err;
$promise->resolve(@results);
}
);
return $promise;
}
Mojo::IOLoop->start;
app->start;