forked from clue/reactphp-block
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-await-any.php
More file actions
40 lines (32 loc) · 1.06 KB
/
02-await-any.php
File metadata and controls
40 lines (32 loc) · 1.06 KB
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
<?php
use Clue\React\Block;
require __DIR__ . '/../vendor/autoload.php';
/**
* @param string $url1
* @param string $url2
* @return Psr\Http\Message\ResponseInterface
* @throws Exception when HTTP request fails
*/
function requestHttpFastestOfMultiple($url1, $url2)
{
// use a unique event loop instance for all parallel operations
$loop = React\EventLoop\Factory::create();
// This example uses an HTTP client
$browser = new React\Http\Browser($loop);
// set up two parallel requests
$promises = array(
$browser->get($url1),
$browser->get($url2)
);
try {
// keep the loop running (i.e. block) until the first response arrives
$fasterResponse = Block\awaitAny($promises, $loop);
// promise successfully fulfilled with $fasterResponse
return $fasterResponse;
} catch (Exception $exception) {
// promise rejected with $exception
throw $exception;
}
}
$first = requestHttpFastestOfMultiple('http://www.google.com/', 'http://www.google.co.uk/');
echo $first->getBody();