The Perl and Raku Conference 2025: Greenville, South Carolina - June 27-29 Learn more

NAME

fs::Promises - Promises interface to nonblocking file system operations

SYNOPSIS

use fs::Promises::Utils qw(await);
# Fancy, but not really useful:
my $fh = await +fs::Promises->open_promise($0);
while ( my $line = await +fs::Promises->readline_promise($fh) ) {
say $line;
}
# Same thing but using the functional interface:
use fs::Promises qw(open_promise readline_promise);
my $fh = await open_promise($0);
while ( my $line = await readline_promise($fh) ) {
say $line;
}
# Actuall async:
use experimental 'signatures';
use fs::Promises qw(open_promise readline_promise);
use fs::Promises::Utils qw(p_while);
await +open_promise($0)->then(sub ($fh) {
return p_while { readline_promise($fh) } sub ($line) {
say $line;
}
});
# Reading four files in parallel:
use experimental 'signatures';
use AnyEvent::XSPromises qw(collect);
use fs::Promises qw(open_promise readline_promise);
use fs::Promises::Utils qw(await p_while);
my $read_file = sub ($fh) {
return p_while { readline_promise($fh) } sub ($line) {
say $line;
}
};
await +collect(
open_promise($0)->then($read_file),
open_promise($0)->then($read_file),
open_promise($0)->then($read_file),
open_promise($0)->then($read_file),
);

DESCRIPTION

fs::Promises is a promises layer around AnyEvent::AIO. If your code is using promises, then you can use this module to do fs-based stuff in an asynchronous way.

DEALING WITH ERRORS

In standard Perl land, syscalls like the ones exposed here generally have this interface:

foo() or die "$!"

That is, you invoke the sycall, and it returns false if the underlaying operation failed, setting $ERRNO / $! in the process.

$! doesn't quite cut it for promises, because by the time your callback is invoked, it is entirely possible for something else to have run, which has now wiped $!.

So instead, all the interfaces here follow the same rough pattern:

foo()->then(sub ($success_result) { ... })
->catch(sub ($errno) { ... })

The real example:

stat_promise($file)->then(
sub ($stat_results) {
# $stat_results has the same 13-element list as 'stat()'
},
sub ($errno) {
my $e_num = 0 + $errno;
my $e_str = "$errno";
warn "stat($file) failed: '$e_str' ($e_num)";
return;
}
);