esroyo / block-react-settle
Add Promise/settle functionality when integrating async components built for ReactPHP in a traditional, blocking environment.
Requires
- php: >=5.4.0
- clue/block-react: ^1.3
- esroyo/react-promise-settle: ^1.0
Requires (Dev)
- phpunit/phpunit: ^7.1 || ^6.4
- react/event-loop: ^1.0
- react/promise: ^2.7
- react/promise-timer: ^1.5
This package is auto-updated.
Last update: 2024-10-27 01:59:29 UTC
README
This library adds settle functionality on top of clue/block-react, which eases the pain of integrating async components into your traditional, synchronous (blocking) application stack.
Installation
composer require esroyo/block-react-settle
Usage
The settle(array $promises, LoopInterface $loop, $timeout = null)
function can be used to wait for ALL of the given promises to resolve or reject.
use Esroyo\React\Block;
$promises = [
$promise1,
$promise2,
];
$allResults = Block\settle($promises, $loop);
foreach ($allResults as $index => $result) {
if ($result['state'] === 'fulfilled') {
echo "Promise $index resolved with: {$result['value']}";
} elseif ($result['state'] === 'rejected') {
// Be aware $result['reason'] might usually be an Exception
// in that case you would use $result['reason']->getMessage()
echo "Promise $index rejected with: {$result['reason']}";
}
}
Once the last promise resolves or rejects, this will return an state associative array containing a "state" key mapping to a valid promise state. If the state of the promise is "fulfilled", the array will contain a "value" key mapping to the fulfilled value of the promise. If the promise is rejected, the array will contain a "reason" key mapping to the rejection reason of the promise.
Array keys will be left intact, i.e. they can be used to correlate the return array to the promises passed.
If no $timeout
is given and either promise stays pending, then this will
potentially wait/block forever until the last promise is settled.
If a $timeout
is given and either promise is still pending once the timeout
triggers, this will cancel()
all pending promises and throw a TimeoutException
.
This implies that if you pass a really small (or negative) value, it will still
start a timer and will thus trigger at the earliest possible time in the future.