forked from reactphp/async
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
224 lines (192 loc) · 6.39 KB
/
functions.php
File metadata and controls
224 lines (192 loc) · 6.39 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<?php
namespace React\Async;
use React\EventLoop\Loop;
use React\Promise\CancellablePromiseInterface;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;
/**
* Block waiting for the given `$promise` to be fulfilled.
*
* ```php
* $result = React\Async\await($promise, $loop);
* ```
*
* This function will only return after the given `$promise` has settled, i.e.
* either fulfilled or rejected.
*
* While the promise is pending, this function will assume control over the event
* loop. Internally, it will `run()` the [default loop](https://github.com/reactphp/event-loop#loop)
* until the promise settles and then calls `stop()` to terminate execution of the
* loop. This means this function is more suited for short-lived promise executions
* when using promise-based APIs is not feasible. For long-running applications,
* using promise-based APIs by leveraging chained `then()` calls is usually preferable.
*
* Once the promise is fulfilled, this function will return whatever the promise
* resolved to.
*
* Once the promise is rejected, this will throw whatever the promise rejected
* with. If the promise did not reject with an `Exception` or `Throwable`, then
* this function will throw an `UnexpectedValueException` instead.
*
* ```php
* try {
* $result = React\Async\await($promise, $loop);
* // promise successfully fulfilled with $result
* echo 'Result: ' . $result;
* } catch (Throwable $e) {
* // promise rejected with $e
* echo 'Error: ' . $e->getMessage();
* }
* ```
*
* @param PromiseInterface $promise
* @return mixed returns whatever the promise resolves to
* @throws \Exception when the promise is rejected with an `Exception`
* @throws \Throwable when the promise is rejected with a `Throwable`
* @throws \UnexpectedValueException when the promise is rejected with an unexpected value (Promise API v1 or v2 only)
*/
function await(PromiseInterface $promise)
{
$wait = true;
$resolved = null;
$exception = null;
$rejected = false;
$promise->then(
function ($c) use (&$resolved, &$wait) {
$resolved = $c;
$wait = false;
Loop::stop();
},
function ($error) use (&$exception, &$rejected, &$wait) {
$exception = $error;
$rejected = true;
$wait = false;
Loop::stop();
}
);
// Explicitly overwrite argument with null value. This ensure that this
// argument does not show up in the stack trace in PHP 7+ only.
$promise = null;
while ($wait) {
Loop::run();
}
if ($rejected) {
// promise is rejected with an unexpected value (Promise API v1 or v2 only)
if (!$exception instanceof \Throwable) {
$exception = new \UnexpectedValueException(
'Promise rejected with unexpected value of type ' . (is_object($exception) ? get_class($exception) : gettype($exception))
);
}
throw $exception;
}
return $resolved;
}
/**
* @param array<callable():PromiseInterface<mixed,Exception>> $tasks
* @return PromiseInterface<array<mixed>,Exception>
*/
function parallel(array $tasks): PromiseInterface
{
$pending = [];
$deferred = new Deferred(function () use (&$pending) {
foreach ($pending as $promise) {
if ($promise instanceof CancellablePromiseInterface) {
$promise->cancel();
}
}
$pending = [];
});
$results = [];
$errored = false;
$numTasks = count($tasks);
if (0 === $numTasks) {
$deferred->resolve($results);
}
$taskErrback = function ($error) use (&$pending, $deferred, &$errored) {
$errored = true;
$deferred->reject($error);
foreach ($pending as $promise) {
if ($promise instanceof CancellablePromiseInterface) {
$promise->cancel();
}
}
$pending = [];
};
foreach ($tasks as $i => $task) {
$taskCallback = function ($result) use (&$results, &$pending, $numTasks, $i, $deferred) {
$results[$i] = $result;
if (count($results) === $numTasks) {
$deferred->resolve($results);
}
};
$promise = call_user_func($task);
assert($promise instanceof PromiseInterface);
$pending[$i] = $promise;
$promise->then($taskCallback, $taskErrback);
if ($errored) {
break;
}
}
return $deferred->promise();
}
/**
* @param array<callable():PromiseInterface<mixed,Exception>> $tasks
* @return PromiseInterface<array<mixed>,Exception>
*/
function series(array $tasks): PromiseInterface
{
$pending = null;
$deferred = new Deferred(function () use (&$pending) {
if ($pending instanceof CancellablePromiseInterface) {
$pending->cancel();
}
$pending = null;
});
$results = [];
/** @var callable():void $next */
$taskCallback = function ($result) use (&$results, &$next) {
$results[] = $result;
$next();
};
$next = function () use (&$tasks, $taskCallback, $deferred, &$results, &$pending) {
if (0 === count($tasks)) {
$deferred->resolve($results);
return;
}
$task = array_shift($tasks);
$promise = call_user_func($task);
assert($promise instanceof PromiseInterface);
$pending = $promise;
$promise->then($taskCallback, array($deferred, 'reject'));
};
$next();
return $deferred->promise();
}
/**
* @param array<callable(mixed=):PromiseInterface<mixed,Exception>> $tasks
* @return PromiseInterface<mixed,Exception>
*/
function waterfall(array $tasks): PromiseInterface
{
$pending = null;
$deferred = new Deferred(function () use (&$pending) {
if ($pending instanceof CancellablePromiseInterface) {
$pending->cancel();
}
$pending = null;
});
/** @var callable $next */
$next = function ($value = null) use (&$tasks, &$next, $deferred, &$pending) {
if (0 === count($tasks)) {
$deferred->resolve($value);
return;
}
$task = array_shift($tasks);
$promise = call_user_func_array($task, func_get_args());
assert($promise instanceof PromiseInterface);
$pending = $promise;
$promise->then($next, array($deferred, 'reject'));
};
$next();
return $deferred->promise();
}