PHP code example of utopia-php / async
1. Go to this page and download the library: Download utopia-php/async 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/ */
utopia-php / async example snippets
use Utopia\Async\Promise;
// Execute and get result
$result = Promise::run(fn() => 42); // Returns: 42
// Async execution with chaining
Promise::async(fn() => 10)
->then(fn($v) => $v * 2)
->then(fn($v) => $v + 5)
->catch(fn($e) => error_log($e->getMessage()))
->finally(fn() => cleanup())
->await(); // Returns: 25
// Execute multiple callables concurrently
$results = Promise::map([
fn() => fetchUser(),
fn() => fetchPosts(),
fn() => fetchComments(),
])->await(); // [user, posts, comments]
// Create resolved/rejected promises
$resolved = Promise::resolve('value');
$rejected = Promise::reject(new Exception('error'));
// Delay execution
Promise::delay(1000)->await(); // Wait 1 second
// Timeout wrapper
Promise::async(fn() => longOperation())
->timeout(5000) // 5 second timeout
->catch(fn($e) => handleTimeout())
->await();
// Wait for all promises
$results = Promise::all([
Promise::async(fn() => fetchUser()),
Promise::async(fn() => fetchPosts()),
Promise::async(fn() => fetchComments()),
])->await(); // [user, posts, comments]
// First to settle wins
$fastest = Promise::race([
Promise::async(fn() => primaryApi()),
Promise::async(fn() => fallbackApi()),
])->await();
// Get all results regardless of success/failure
$results = Promise::allSettled([
Promise::async(fn() => maySucceed()),
Promise::async(fn() => mayFail()),
])->await();
// [
// ['status' => 'fulfilled', 'value' => ...],
// ['status' => 'rejected', 'reason' => Exception]
// ]
// First successful result
$value = Promise::any([
Promise::async(fn() => tryFirst()),
Promise::async(fn() => trySecond()),
])->await();
use Utopia\Async\Parallel;
// Single task
$result = Parallel::run(fn() => expensiveCalculation());
// With arguments
$result = Parallel::run(fn($x, $y) => $x + $y, 10, 20); // Returns: 30
// Multiple tasks
$results = Parallel::all([
fn() => task1(),
fn() => task2(),
fn() => task3(),
]); // [result1, result2, result3]
$items = [1, 2, 3, 4, 5, 6, 7, 8];
// Parallel map - transforms each item
$squared = Parallel::map($items, fn($n) => $n ** 2);
// [1, 4, 9, 16, 25, 36, 49, 64]
// Specify worker count
$results = Parallel::map($items, fn($n) => process($n), 4); // 4 workers
// ForEach - side effects only, no return values
Parallel::forEach($files, fn($file) => processFile($file), 8);
// Limit concurrent execution
$tasks = [];
for ($i = 0; $i < 100; $i++) {
$tasks[] = fn() => processItem($i);
}
// Max 10 concurrent tasks
$results = Parallel::pool($tasks, 10);
// Optional: manually shutdown to release resources early
Parallel::shutdown();
// Create a custom pool (not auto-cleaned, you manage its lifecycle)
$pool = Parallel::createPool(16); // 16 workers
use Utopia\Async\Promise;
use Utopia\Async\Promise\Adapter\Sync;
Promise::setAdapter(Sync::class);
use Utopia\Async\Exception\Timeout;
use Utopia\Async\Exception\Serialization;
try {
Promise::async(fn() => riskyOperation())
->timeout(5000)
->await();
} catch (Timeout $e) {
// Handle timeout
} catch (Serialization $e) {
// Handle serialization failure
}
use Utopia\Async\Parallel;
// Get current values
Parallel::getMaxSerializedSize(); // 10 MB (10485760 bytes)
Parallel::getMaxTaskTimeoutSeconds(); // 30 seconds
Parallel::getDeadlockDetectionInterval(); // 5 seconds
Parallel::getMemoryThresholdForGc(); // 50 MB (52428800 bytes)
Parallel::getStreamSelectTimeoutUs(); // 100ms (100000 μs)
Parallel::getWorkerSleepDurationUs(); // 10ms (10000 μs)
Parallel::getGcCheckInterval(); // 10 tasks
// Set custom values
Parallel::setMaxTaskTimeoutSeconds(60); // Increase timeout to 60s
Parallel::setMemoryThresholdForGc(104857600); // 100 MB
// Reset all to defaults
Parallel::resetConfig();
use Utopia\Async\Promise;
// Get current values
Promise::getSleepDurationUs(); // 100 μs
Promise::getMaxSleepDurationUs(); // 10ms (10000 μs)
Promise::getCoroutineSleepDurationS(); // 1ms (0.001 seconds)
// Set custom values
Promise::setSleepDurationUs(200); // Increase initial sleep
Promise::setMaxSleepDurationUs(50000); // 50ms max backoff
// Reset all to defaults
Promise::resetConfig();
bash
composer bash
# Run benchmarks with default settings (5 iterations, 50% load)
php benchmarks/Benchmark.php
# Higher iteration count for more stable results
php benchmarks/Benchmark.php --iterations=10
# Adjust workload intensity (1-100, default 50)
php benchmarks/Benchmark.php --load=75
# JSON output for charting and analysis
php benchmarks/Benchmark.php --json
# Combined options
php benchmarks/Benchmark.php --iterations=10 --load=75 --json