onComplete event for async?
d47081 opened this issue · comments
I'm trying to execute function by \Amp\async
$future = \Amp\async(
function(): void
{
// some action...
}
);
but how can I catch completed event for this $future
?
like in JS - on complete event or something like that
$future->on('complete', function() {
// some action for complete event...
});
Just call map
$future->map(function() {
// do sth when success
});
$future->catch(function($e) {
// do sth when error
});
$future->finally(function() {
// do sth when completed
});
Thanks, but I can't see any print yet:
$future = \Amp\async(
function()
{
print 0;
}
);
$future->map(function() {
// do sth when success
print 1;
});
$future->catch(function($e) {
// do sth when error
print 2;
});
$future->finally(function() {
// do sth when completed
print 3;
});
I just want to make some action (hide loading bar) in main application thread.
Or at least print 1-3
on print 0
completed
You need await()
for future, or php-cli will not wait for async.
$future = \Amp\async(
function()
{
print 0;
}
);
$future->map(function() {
// do sth when success
print 1;
});
$future->catch(function($e) {
// do sth when error
print 2;
});
$future->finally(function() {
// do sth when completed
print 3;
});
$future->await();
But it make the main thread pending for result like sync..
Your main thread will always have to wait for all async events you want to have processed before the process dies.
My app have build in \Gtk::timeout_add
method to listen Amp
status updates on frame background, here is an example:
$future = \Amp\async(
function()
{
print 0;
}
);
\Gtk::timeout_add( // loop with 1 seconds delay
1000,
function() use ($future)
{
$future->finally(function() {
print 1;
});
# $future->await(); // not wanted here
}
);
But $future->await();
freezes application because pending for sync response. And I haven't any print
without await
.
In other words, I need to check status only, without sync/await marker.
@d47081 Why did you do finally
after 1 second? finally
must be called on $future immediately.
And what is \Gtk::timeout_add, is this timeout depends on php main thread?
If not, you should do like this:
$future = \Amp\async(
function()
{
print 0;
}
);
$future->finally(function() {
print 1;
});
\Gtk::timeout_add( // loop with 1 seconds delay
1000,
function() use ($future)
{
//do something here
}
);
$future->await();
Thanks but finally solved my task with shared memory and https://www.php.net/manual/en/function.pcntl-fork.php
because no idea what this library do as \Amp\async
does not return $future->finally
result into the main thread.
You should figure out what is finally, finally is not for result returning, it's for to do something after whatever a Future
is success of failed.
It likes:
try {
// your job in async...
// means $future->map() here
} catch (\Throwable $e) {
// means $future->catch() here
} finally {
// means $future->finally() here
}