PHP code example of reinfyteam / libasync
1. Go to this page and download the library: Download reinfyteam/libasync library. Choose the download type require. 2. Extract the ZIP file and open the index.php. 3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
reinfyteam / libasync example snippets
use function libasync\async;
use function libasync\defer;
use function libasync\delay;
use function libasync\joined;
use function libasync\may_drop;
use function libasync\thread;
use function libasync\timeout;
use function libasync\trap;
// Run an async task
async(static function() {
// Do async work and return a value
})->panic();
async(static function() {
// Run a task in a separate thread (or process, depending on runtime)
$threadResult = yield from thread(static fn() => ['a' => 1, 'b' => 2]);
// $threadResult === ['a' => 1, 'b' => 2]
// Trap example: coroutine pauses if condition fails
trap(static fn() => someConditionCheck());
// Deferred cleanup: executed when coroutine finishes
defer(static fn() => echo "Cleaning up...\n");
// Mark a coroutine as "joined" to ensure it completes
joined();
// Or mark it as "may_drop" for non-critical tasks
may_drop();
// Set a timeout for the currently running coroutine (seconds)
timeout(5.0); // throws if task not completed in 5s
// Delay execution of a closure by ticks (1 tick = 50ms)
yield from delay(static fn() => echo "Delayed hello\n", 10);
// Player-specific trap (PocketMine-MP)
if (class_exists(\pocketmine\player\Player::class)) {
$player = /* get Player instance */;
trap_online($player); // coroutine pauses if player is offline
}
})->panic();