2 namespace GuzzleHttp\Promise;
5 * Get the global task queue used for promise resolution.
7 * This task queue MUST be run in an event loop in order for promises to be
8 * settled asynchronously. It will be automatically run when synchronously
9 * waiting on a promise.
12 * while ($eventLoop->isRunning()) {
13 * GuzzleHttp\Promise\queue()->run();
17 * @param TaskQueueInterface $assign Optionally specify a new queue instance.
19 * @return TaskQueueInterface
21 function queue(TaskQueueInterface $assign = null)
28 $queue = new TaskQueue();
35 * Adds a function to run in the task queue when it is next `run()` and returns
36 * a promise that is fulfilled or rejected with the result.
38 * @param callable $task Task function to run.
40 * @return PromiseInterface
42 function task(callable $task)
45 $promise = new Promise([$queue, 'run']);
46 $queue->add(function () use ($task, $promise) {
48 $promise->resolve($task());
49 } catch (\Throwable $e) {
51 } catch (\Exception $e) {
60 * Creates a promise for a value if the value is not a promise.
62 * @param mixed $value Promise or value.
64 * @return PromiseInterface
66 function promise_for($value)
68 if ($value instanceof PromiseInterface) {
72 // Return a Guzzle promise that shadows the given promise.
73 if (method_exists($value, 'then')) {
74 $wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null;
75 $cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
76 $promise = new Promise($wfn, $cfn);
77 $value->then([$promise, 'resolve'], [$promise, 'reject']);
81 return new FulfilledPromise($value);
85 * Creates a rejected promise for a reason if the reason is not a promise. If
86 * the provided reason is a promise, then it is returned as-is.
88 * @param mixed $reason Promise or reason.
90 * @return PromiseInterface
92 function rejection_for($reason)
94 if ($reason instanceof PromiseInterface) {
98 return new RejectedPromise($reason);
102 * Create an exception for a rejected promise value.
104 * @param mixed $reason
106 * @return \Exception|\Throwable
108 function exception_for($reason)
110 return $reason instanceof \Exception || $reason instanceof \Throwable
112 : new RejectionException($reason);
116 * Returns an iterator for the given value.
118 * @param mixed $value
122 function iter_for($value)
124 if ($value instanceof \Iterator) {
126 } elseif (is_array($value)) {
127 return new \ArrayIterator($value);
129 return new \ArrayIterator([$value]);
134 * Synchronously waits on a promise to resolve and returns an inspection state
137 * Returns a state associative array containing a "state" key mapping to a
138 * valid promise state. If the state of the promise is "fulfilled", the array
139 * will contain a "value" key mapping to the fulfilled value of the promise. If
140 * the promise is rejected, the array will contain a "reason" key mapping to
141 * the rejection reason of the promise.
143 * @param PromiseInterface $promise Promise or value.
147 function inspect(PromiseInterface $promise)
151 'state' => PromiseInterface::FULFILLED,
152 'value' => $promise->wait()
154 } catch (RejectionException $e) {
155 return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()];
156 } catch (\Throwable $e) {
157 return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
158 } catch (\Exception $e) {
159 return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
164 * Waits on all of the provided promises, but does not unwrap rejected promises
165 * as thrown exception.
167 * Returns an array of inspection state arrays.
169 * @param PromiseInterface[] $promises Traversable of promises to wait upon.
172 * @see GuzzleHttp\Promise\inspect for the inspection state array format.
174 function inspect_all($promises)
177 foreach ($promises as $key => $promise) {
178 $results[$key] = inspect($promise);
185 * Waits on all of the provided promises and returns the fulfilled values.
187 * Returns an array that contains the value of each promise (in the same order
188 * the promises were provided). An exception is thrown if any of the promises
191 * @param mixed $promises Iterable of PromiseInterface objects to wait on.
194 * @throws \Exception on error
195 * @throws \Throwable on error in PHP >=7
197 function unwrap($promises)
200 foreach ($promises as $key => $promise) {
201 $results[$key] = $promise->wait();
208 * Given an array of promises, return a promise that is fulfilled when all the
209 * items in the array are fulfilled.
211 * The promise's fulfillment value is an array with fulfillment values at
212 * respective positions to the original array. If any promise in the array
213 * rejects, the returned promise is rejected with the rejection reason.
215 * @param mixed $promises Promises or values.
217 * @return PromiseInterface
219 function all($promises)
224 function ($value, $idx) use (&$results) {
225 $results[$idx] = $value;
227 function ($reason, $idx, Promise $aggregate) {
228 $aggregate->reject($reason);
230 )->then(function () use (&$results) {
237 * Initiate a competitive race between multiple promises or values (values will
238 * become immediately fulfilled promises).
240 * When count amount of promises have been fulfilled, the returned promise is
241 * fulfilled with an array that contains the fulfillment values of the winners
242 * in order of resolution.
244 * This prommise is rejected with a {@see GuzzleHttp\Promise\AggregateException}
245 * if the number of fulfilled promises is less than the desired $count.
247 * @param int $count Total number of promises.
248 * @param mixed $promises Promises or values.
250 * @return PromiseInterface
252 function some($count, $promises)
259 function ($value, $idx, PromiseInterface $p) use (&$results, $count) {
260 if ($p->getState() !== PromiseInterface::PENDING) {
263 $results[$idx] = $value;
264 if (count($results) >= $count) {
268 function ($reason) use (&$rejections) {
269 $rejections[] = $reason;
272 function () use (&$results, &$rejections, $count) {
273 if (count($results) !== $count) {
274 throw new AggregateException(
275 'Not enough promises to fulfill count',
280 return array_values($results);
286 * Like some(), with 1 as count. However, if the promise fulfills, the
287 * fulfillment value is not an array of 1 but the value directly.
289 * @param mixed $promises Promises or values.
291 * @return PromiseInterface
293 function any($promises)
295 return some(1, $promises)->then(function ($values) { return $values[0]; });
299 * Returns a promise that is fulfilled when all of the provided promises have
300 * been fulfilled or rejected.
302 * The returned promise is fulfilled with an array of inspection state arrays.
304 * @param mixed $promises Promises or values.
306 * @return PromiseInterface
307 * @see GuzzleHttp\Promise\inspect for the inspection state array format.
309 function settle($promises)
315 function ($value, $idx) use (&$results) {
316 $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value];
318 function ($reason, $idx) use (&$results) {
319 $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason];
321 )->then(function () use (&$results) {
328 * Given an iterator that yields promises or values, returns a promise that is
329 * fulfilled with a null value when the iterator has been consumed or the
330 * aggregate promise has been fulfilled or rejected.
332 * $onFulfilled is a function that accepts the fulfilled value, iterator
333 * index, and the aggregate promise. The callback can invoke any necessary side
334 * effects and choose to resolve or reject the aggregate promise if needed.
336 * $onRejected is a function that accepts the rejection reason, iterator
337 * index, and the aggregate promise. The callback can invoke any necessary side
338 * effects and choose to resolve or reject the aggregate promise if needed.
340 * @param mixed $iterable Iterator or array to iterate over.
341 * @param callable $onFulfilled
342 * @param callable $onRejected
344 * @return PromiseInterface
348 callable $onFulfilled = null,
349 callable $onRejected = null
351 return (new EachPromise($iterable, [
352 'fulfilled' => $onFulfilled,
353 'rejected' => $onRejected
358 * Like each, but only allows a certain number of outstanding promises at any
361 * $concurrency may be an integer or a function that accepts the number of
362 * pending promises and returns a numeric concurrency limit value to allow for
363 * dynamic a concurrency size.
365 * @param mixed $iterable
366 * @param int|callable $concurrency
367 * @param callable $onFulfilled
368 * @param callable $onRejected
370 * @return PromiseInterface
375 callable $onFulfilled = null,
376 callable $onRejected = null
378 return (new EachPromise($iterable, [
379 'fulfilled' => $onFulfilled,
380 'rejected' => $onRejected,
381 'concurrency' => $concurrency
386 * Like each_limit, but ensures that no promise in the given $iterable argument
387 * is rejected. If any promise is rejected, then the aggregate promise is
388 * rejected with the encountered rejection.
390 * @param mixed $iterable
391 * @param int|callable $concurrency
392 * @param callable $onFulfilled
394 * @return PromiseInterface
396 function each_limit_all(
399 callable $onFulfilled = null
405 function ($reason, $idx, PromiseInterface $aggregate) {
406 $aggregate->reject($reason);
412 * Returns true if a promise is fulfilled.
414 * @param PromiseInterface $promise
418 function is_fulfilled(PromiseInterface $promise)
420 return $promise->getState() === PromiseInterface::FULFILLED;
424 * Returns true if a promise is rejected.
426 * @param PromiseInterface $promise
430 function is_rejected(PromiseInterface $promise)
432 return $promise->getState() === PromiseInterface::REJECTED;
436 * Returns true if a promise is fulfilled or rejected.
438 * @param PromiseInterface $promise
442 function is_settled(PromiseInterface $promise)
444 return $promise->getState() !== PromiseInterface::PENDING;
450 * @param callable $generatorFn
452 * @return PromiseInterface
454 function coroutine(callable $generatorFn)
456 return new Coroutine($generatorFn);