Skip to content

Instantly share code, notes, and snippets.

@azjezz
Last active December 30, 2021 15:27
Show Gist options
  • Save azjezz/d2e7a516965e2b97fe9900bda28f15cc to your computer and use it in GitHub Desktop.
Save azjezz/d2e7a516965e2b97fe9900bda28f15cc to your computer and use it in GitHub Desktop.
<?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