Last active
December 30, 2021 15:27
-
-
Save azjezz/d2e7a516965e2b97fe9900bda28f15cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use Psl\Async; | |
use Psl\IO; | |
require 'vendor/autoload.php'; | |
function fetch(string $id): string { | |
IO\write_line('Fetching resource with id #%s', $id); | |
Async\sleep(1); // mocking an I/O operation | |
return $id; | |
} | |
final class Service { | |
private array $cache = []; | |
public function get(string $id): string | |
{ | |
if (isset($this->cache[$id])) { | |
return $this->cache[$id]; | |
} | |
$item = fetch($id); | |
$this->cache[$id] = $item; | |
return $item; | |
} | |
} | |
Async\main(static function(): int { | |
$service = new Service(); | |
[$one, $two] = Async\concurrently([ | |
static fn() => $service->get('foo'), | |
static fn() => $service->get('foo'), | |
]); | |
var_dump($one, $two); | |
$sequence = new Async\Sequence($service->get(...)); | |
[$one, $two] = Async\concurrently([ | |
static fn() => $sequence->waitFor('bar'), | |
static fn() => $sequence->waitFor('bar'), | |
]); | |
var_dump($one, $two); | |
return 0; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment