-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
any.php
47 lines (40 loc) · 1.11 KB
/
any.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
42
43
44
45
46
47
<?php
declare(strict_types=1);
namespace Psl\Async;
use Psl\Async\Exception\CompositeException;
use Throwable;
/**
* Unwraps the first successfully completed awaitable.
*
* If you want the first awaitable completed, successful or not, use {@see first()} instead.
*
* @template T
*
* @param iterable<Awaitable<T>> $awaitables
*
* @throws Exception\CompositeException If all $awaitables errored.
* @throws Exception\InvalidArgumentException If $awaitables is empty.
*
* @return T
*/
function any(iterable $awaitables): mixed
{
$errors = [];
foreach (Awaitable::iterate($awaitables) as $first) {
try {
$result = $first->await();
foreach ($awaitables as $awaitable) {
if ($awaitable !== $first) {
$awaitable->ignore();
}
}
return $result;
} catch (Throwable $exception) {
$errors[] = $exception;
}
}
if ([] === $errors) {
throw new Exception\InvalidArgumentException('$awaitables must be a non-empty-iterable.');
}
throw new CompositeException($errors);
}