-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy path1-concurrent-fetch.php
41 lines (32 loc) · 1.04 KB
/
1-concurrent-fetch.php
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
40
41
<?php
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\all($futures);
foreach ($bodies as $uri => $body) {
print $uri . " - " . \strlen($body) . " bytes" . PHP_EOL;
}
} catch (HttpException $error) {
// If something goes wrong Amp will throw the exception where the promise was yielded.
// The HttpClient::request() method itself will never throw directly, but returns a promise.
echo $error;
}