Skip to content

Commit

Permalink
Add parallel request example
Browse files Browse the repository at this point in the history
  • Loading branch information
kelunik committed Jul 13, 2017
1 parent 6557178 commit d90d6ef
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions examples/6-parallel-requests.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

use Amp\Artax\Response;
use Amp\Loop;

require __DIR__ . '/../vendor/autoload.php';

Loop::run(function () {
$uris = [
"https://google.com/",
"https://github.com/",
"https://stackoverflow.com/",
];

// Instantiate the HTTP client
$client = new Amp\Artax\DefaultClient;

$requestHandler = function (string $uri) use ($client) {
/** @var Response $response */
$response = yield $client->request($uri);

return $response->getBody();
};

try {
$promises = [];

foreach ($uris as $uri) {
$promises[$uri] = Amp\call($requestHandler, $uri);
}

$bodies = yield $promises;

foreach ($bodies as $uri => $body) {
print $uri . " - " . \strlen($body) . " bytes" . PHP_EOL;
}
} catch (Amp\Artax\HttpException $error) {
// If something goes wrong Amp will throw the exception where the promise was yielded.
// The Client::request() method itself will never throw directly, but returns a promise.
echo $error;
}
});

0 comments on commit d90d6ef

Please sign in to comment.