Last updated: 2026-10-25
Back to README
- PHP 7.4 or higher
- Composer
react/promise^2.8 || ^3.0react/event-loop^1.1 || ^2.0
composer require pardnchiu/asyncgit clone https://github.com/pardnio/php-async.git
cd php-async
composer installThe package maps PD\ to src/ via PSR-4; load the Composer autoloader and use PD\Async.
Each task is one array entry: the key is the task name, method is the callable to run, and tasks lists prerequisite task names (omit it or pass an empty array).
<?php
require __DIR__ . '/vendor/autoload.php';
use PD\Async;
$tasks = [
'fetchUser' => [
'method' => function () {
return ['id' => 1, 'name' => 'Pardn'];
},
],
'fetchOrders' => [
'method' => function () {
return [101, 102];
},
'tasks' => ['fetchUser'],
],
];
Async::run($tasks)
->then(function (array $results) {
// $results is keyed by task name
print_r($results['fetchUser']);
print_r($results['fetchOrders']);
})
->catch(function (\Throwable $error) {
echo 'Error: ' . $error->getMessage();
});A circular dependency is thrown synchronously during sorting and never reaches the promise catch; an exception thrown inside a task rejects the returned promise. Handle both separately.
<?php
require __DIR__ . '/vendor/autoload.php';
use PD\Async;
$tasks = [
'a' => ['method' => fn () => 'A', 'tasks' => ['b']],
'b' => ['method' => fn () => 'B', 'tasks' => ['a']],
];
try {
Async::run($tasks)
->then(function (array $results) {
print_r($results);
})
->catch(function (\Throwable $error) {
// Exception thrown inside a task
error_log('Task failed: ' . $error->getMessage());
});
} catch (\Exception $e) {
// Circular dependency: Circular dependency detected: a
error_log($e->getMessage());
}public static function run(array $tasks): React\Promise\PromiseInterfaceBuilds the dependency graph, sorts it topologically, creates a Deferred promise per task, and aggregates them with Promise\all; once everything settles it runs the event loop and resolves with the result array.
| Field | Type | Required | Description |
|---|---|---|---|
| Array key | string |
Yes | Task name, also the key in the result array |
method |
callable |
Yes | Called with no arguments; its return value becomes the task result |
tasks |
string[] |
No | Prerequisite task names; omit or leave empty for no dependency |
| Case | Outcome |
|---|---|
| All tasks succeed | Promise resolves with [taskName => returnValue] |
A task throws \Exception |
That task's promise rejects and the aggregate promise enters catch |
| Dependencies form a cycle | run() throws \Exception("Circular dependency detected: <task>") synchronously |
©️ 2024 邱敬幃 Pardn Chiu