-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy path1-concurrent-fetch.php
More file actions
39 lines (30 loc) · 905 Bytes
/
1-concurrent-fetch.php
File metadata and controls
39 lines (30 loc) · 905 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php declare(strict_types=1);
use Amp\Future;
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\HttpException;
use Amp\Http\Client\Request;
use function Amp\async;
require __DIR__ . '/../.helper/functions.php';
$uris = [
"https://google.com/",
"https://github.com/",
"https://stackoverflow.com/",
];
// Instantiate the HTTP client
$client = HttpClientBuilder::buildDefault();
$requestHandler = static function (string $uri) use ($client): string {
$response = $client->request(new Request($uri));
return $response->getBody()->buffer();
};
try {
$futures = [];
foreach ($uris as $uri) {
$futures[$uri] = async(fn () => $requestHandler($uri));
}
$bodies = Future\await($futures);
foreach ($bodies as $uri => $body) {
print $uri . " - " . strlen($body) . " bytes" . PHP_EOL;
}
} catch (HttpException $error) {
echo $error;
}