### Install Guzzle Promises Source: https://github.com/guzzle/promises/blob/2.5/README.md Use Composer to install the Guzzle Promises library. This command adds the library as a dependency to your project. ```shell composer require guzzlehttp/promises ``` -------------------------------- ### PromiseInterface Example Usage Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/interfaces.md Demonstrates how to use the PromiseInterface with different promise implementations, applying fulfillment and rejection handlers. ```php use GuzzleHttp\Promise\PromiseInterface; function processPromise(PromiseInterface $promise): PromiseInterface { return $promise ->then(function ($value) { return $value * 2; }) ->otherwise(function ($reason) { return 0; // Default on error }); } // Works with any implementation processPromise(new Promise()); processPromise(new FulfilledPromise('value')); processPromise(new Coroutine(function () { /* ... */ })); ``` -------------------------------- ### Execute and Wait for Promise Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/interfaces.md This example shows how to obtain a promise from a PromisorInterface object and wait for its result. Ensure the object passed implements PromisorInterface. ```php use GuzzleHttp\Promise\PromisorInterface; use GuzzleHttp\Promise\EachPromise; function executeAndWait(PromisorInterface $promiser): void { $promise = $promiser->promise(); $result = $promise->wait(); echo $result; } // EachPromise implements PromisorInterface $each = new EachPromise($items, [ 'fulfilled' => function ($value) { /* ... */ } ]); executeAndWait($each); ``` -------------------------------- ### Example Promise Imports Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Commonly used Guzzle Promises classes and interfaces for import. ```php use GuzzleHttp\Promise\Promise; use GuzzleHttp\Promise\PromiseInterface; use GuzzleHttp\Promise\Utils; use GuzzleHttp\Promise\Each; use GuzzleHttp\Promise\Coroutine; use GuzzleHttp\Promise\RejectionException; ``` -------------------------------- ### AggregateException Handling Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/errors.md This example demonstrates how to catch an AggregateException and retrieve the individual rejection reasons from failed promises. ```APIDOC ## AggregateException **Class:** `GuzzleHttp\Promise\AggregateException` **Extends:** `RejectionException` **Trigger Condition:** Thrown when `Utils::some()` or `Utils::any()` do not collect enough fulfilled promises before all promises are exhausted. **Characteristics:** - Contains all rejection reasons from failed promises. - The `reason` property is an array of rejection reasons. - The exception message includes the count of rejected promises. **How to Catch:** ```php use GuzzleHttp\Promise\AggregateException; use GuzzleHttp\Promise\Utils; $promises = [ new RejectedPromise('error 1'), new RejectedPromise('error 2'), ]; Utils::some(2, $promises)->then( null, function ($reason) { if ($reason instanceof AggregateException) { $reasons = $reason->getReason(); // ['error 1', 'error 2'] foreach ($reasons as $r) { echo "Rejection: $r\n"; } } } ); ``` **Trigger Condition Details:** ```php // Example for Utils::some() // some(3, [promise1, promise2]) where only 1 fulfills Utils::some(3, $promises)->then( null, function ($reason) { // AggregateException thrown // getReason(): array of 2 rejection reasons } ); // Example for Utils::any() // any(promises) where none are fulfilled Utils::any($allRejected)->then( null, function ($reason) { // AggregateException thrown (equivalent to some(1, ...)) // getReason(): array of all rejection reasons } ); ``` ``` -------------------------------- ### Combining Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Examples of combining multiple promises into a single result. ```php Utils::all($promises) ``` ```php Utils::some(2, $promises) ``` ```php Utils::any($promises) ``` ```php Utils::settle($promises) ``` -------------------------------- ### Processing an Array of Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each.md An example of using Each::of to process an array of promises, echoing the result of each promise and a final 'Done' message. ```php use GuzzleHttp\Promise\Each; use GuzzleHttp\Promise\Utils; $promises = [ Utils::task(function () { return 'result1'; }), Utils::task(function () { return 'result2'; }), Utils::task(function () { return 'result3'; }), ]; Each::of($promises, function ($value, $index) { echo "[$index] $value\n"; } )->then(function () { echo "Done\n"; }); Utils::queue()->run(); ``` -------------------------------- ### Namespace and Imports Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Specifies the namespace for all Guzzle Promises classes and provides example import statements. ```APIDOC ## Namespace and Imports All classes and interfaces are in the `GuzzleHttp\Promise` namespace. ### Example Imports: ```php use GuzzleHttp\Promise\Promise; use GuzzleHttp\Promise\PromiseInterface; use GuzzleHttp\Promise\Utils; use GuzzleHttp\Promise\Each; use GuzzleHttp\Promise\Coroutine; use GuzzleHttp\Promise\RejectionException; ``` ``` -------------------------------- ### Sequential Promise Chaining with Coroutine Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/coroutine.md Demonstrates sequential execution of asynchronous operations using Coroutine, ensuring each promise resolves before the next starts. ```php use GuzzleHttp\Promise\Coroutine; use GuzzleHttp\Promise\FulfilledPromise; Coroutine::of(function () { // These execute sequentially $user = yield fetchUser(1); $profile = yield fetchProfile($user['id']); $posts = yield fetchPosts($user['id']); return [ 'user' => $user, 'profile' => $profile, 'posts' => $posts, ]; })->then(function ($_data) { echo json_encode($_data); }); ``` -------------------------------- ### Promise Chaining Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/promise.md Illustrates how to chain multiple promise operations together. The result of one `then()` callback is passed to the next, allowing for sequential asynchronous operations. ```php $promise = new Promise(); $promise ->then(function ($value) { return $value . ' processed'; }) ->then(function ($result) { echo $result; }); $promise->resolve('Data'); // Outputs: "Data processed" ``` -------------------------------- ### Controlling Concurrency with Each::ofLimit Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each.md Shows how to limit the number of concurrent requests when processing an array of promises using Each::ofLimit. This example fetches URLs and saves their content. ```php use GuzzleHttp\Promise\Each; // Fetch 100 URLs with max 5 concurrent requests $promises = array_map('fetch_url_async', $urls); Each::ofLimit($promises, 5, function ($body, $url) { file_put_contents("cache/$url.html", $body); echo "Downloaded: $url\n"; }, function ($reason, $url) { echo "Failed to download $url: $reason\n"; } )->then(function () { echo "All downloads complete\n"; }); ``` -------------------------------- ### Short-Circuiting on Error Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each.md An example demonstrating how to short-circuit the iteration when an error occurs by rejecting the aggregate promise in the onRejected callback. ```php use GuzzleHttp\Promise\Each; Each::of($promises, function ($value, $index) { echo "Item $index\n"; }, function ($reason, $index, $aggregate) { echo "Error at $index: $reason\n"; // Stop processing remaining items $aggregate->reject(new \Exception("Stopping at item $index")); } ); ``` -------------------------------- ### Custom TaskQueue Implementation Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/interfaces.md Example of a custom implementation of the TaskQueueInterface. This class manages tasks in a simple array and executes them in FIFO order. Remember to register your custom queue using Utils::queue(). ```php class CustomTaskQueue implements TaskQueueInterface { private $tasks = []; public function isEmpty(): bool { return empty($this->tasks); } public function add(callable $task): void { $this->tasks[] = $task; } public function run(): void { while ($task = array_shift($this->tasks)) { $task(); } } } // Register custom queue Utils::queue(new CustomTaskQueue()); ``` -------------------------------- ### OnFulfilled Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A callback invoked when a promise is fulfilled. The return value becomes the resolution value for the returned promise. ```php $onFulfilled = function ($value) { return $value * 2; }; $promise->then($onFulfilled); ``` -------------------------------- ### WaitFn Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A callback invoked when `wait()` is called on a pending promise. Expected to call `resolve()` or `reject()` on the promise. If an exception is thrown, the promise is rejected. ```php $waitFn = function () use (&$promise) { $promise->resolve('waited value'); }; $promise = new Promise($waitFn); ``` -------------------------------- ### ConcurrencyFn Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A dynamic concurrency function that determines how many promises can run concurrently based on the count of currently pending operations. ```php Each::ofLimit($promises, function ($pending) { // Increase concurrency as items complete return 5 + intval($pending / 10); }, $onFulfilled); ``` -------------------------------- ### Wait for any promise to fulfill Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/utils.md Use `Utils::any` to get a promise that fulfills with the value of the first promise that fulfills. This is similar to `some()` with `count=1`, but it returns the fulfillment value directly, not as an array. ```php use GuzzleHttp\Promise\Utils; $promises = [ new RejectedPromise('error 1'), new RejectedPromise('error 2'), new FulfilledPromise('success'), ]; Utils::any($promises)->then(function ($value) { echo $value; // "success" (not wrapped in array) }); ``` -------------------------------- ### Task Queue with Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/task-queue.md Demonstrates creating a task queue, resolving a promise, and running the queue to execute registered callbacks. ```php use GuzzleHttp\Promise\Promise; use GuzzleHttp\Promise\Utils; $queue = Utils::queue(); // Create a pending promise $promise = new Promise(); // Register callbacks $promise->then(function ($value) { echo "Received: $value\n"; }); // Resolve the promise (queues the callback) $promise->resolve('data'); echo "Promise is pending\n"; // Run the queue to execute callbacks $queue->run(); echo "Done\n"; // Output: // Promise is pending // Received: data // Done ``` -------------------------------- ### Create and Resolve a Basic Promise Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/promise.md Demonstrates how to create a new Promise, register success and failure callbacks using `then()`, and resolve the promise with a value. ```php use GuzzleHttp\Promise\Promise; $promise = new Promise(); // Register callbacks $promise->then( function ($value) { echo "Success: " . $value; }, function ($reason) { echo "Failed: " . $reason; } ); // Resolve the promise $promise->resolve('Operation completed'); ``` -------------------------------- ### Creating Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Demonstrates various ways to create new promises. ```php new Promise() ``` ```php new FulfilledPromise($value) ``` ```php new RejectedPromise($reason) ``` ```php Create::promiseFor($value) ``` ```php Coroutine::of($generatorFn) ``` -------------------------------- ### Observe Promise State Transitions Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/is.md Illustrates how to check a promise's state at different points in its lifecycle, from initial pending to fulfilled, using Is::pending(), Is::fulfilled(), and Is::settled(). ```php use GuzzleHttp\Promise\Is; use GuzzleHttp\Promise\Promise; $promise = new Promise(); echo "Initial: " . $promise->getState() . "\n"; echo Is::pending($promise) ? "✓ pending" : "✗ not pending"; echo "\n"; $promise->resolve('value'); echo "After resolve: " . $promise->getState() . "\n"; echo Is::fulfilled($promise) ? "✓ fulfilled" : "✗ not fulfilled"; echo "\n"; echo Is::settled($promise) ? "✓ settled" : "✗ not settled"; echo "\n"; ``` -------------------------------- ### Getting Promise State Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/promise.md The `getState` method returns the current state of the promise, which can be 'pending', 'fulfilled', or 'rejected'. ```php public function getState(): string ``` ```php $promise = new Promise(); echo $promise->getState(); // "pending" $promise->resolve('value'); echo $promise->getState(); // "fulfilled" ``` -------------------------------- ### EachPromise vs. Each::of Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each-promise.md Demonstrates the equivalence between using the static Each::of method and instantiating EachPromise directly. Use Each::of for simpler cases. ```php Each::of($promises, $onFulfilled, $onRejected); new EachPromise($promises, [ 'fulfilled' => $onFulfilled, 'rejected' => $onRejected, ])->promise(); ``` -------------------------------- ### Get Coroutine State Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/coroutine.md Use `getState` to retrieve the current state of the coroutine, which can be PENDING, FULFILLED, or REJECTED. ```php public function getState(): string ``` -------------------------------- ### Get State of Rejected Promise Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/rejected-promise.md Returns the current state of the promise, which will always be 'rejected' for a RejectedPromise instance. ```php $promise = new RejectedPromise('reason'); echo $promise->getState(); // "rejected" ``` -------------------------------- ### Instantiate EachPromise with Callbacks and Concurrency Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each-promise.md Demonstrates how to create an EachPromise instance, providing fulfillment and rejection callbacks, and setting a concurrency limit of 2. The resulting promise is then used to track the completion of all iterated promises. ```php use GuzzleHttp\Promise\EachPromise; $each = new EachPromise( [promise1(), promise2(), promise3()], [ 'fulfilled' => function ($value, $index) { echo "[$index] Success: $value\n"; }, 'rejected' => function ($reason, $index) { echo "[$index] Error: $reason\n"; }, 'concurrency' => 2, // Max 2 concurrent ] ); $promise = $each->promise(); $promise->then(function () { echo "All done\n"; }); ``` -------------------------------- ### Get state of FulfilledPromise Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/fulfilled-promise.md Retrieve the state of the promise using `getState()`. For a `FulfilledPromise`, this will always return 'fulfilled'. ```php $promise = new FulfilledPromise('value'); echo $promise->getState(); // "fulfilled" ``` -------------------------------- ### Type Hints for Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md Demonstrates how to use type hints for `PromiseInterface` and `PromisorInterface` in function signatures for better code clarity and static analysis. ```php function processResult(PromiseInterface $promise): PromiseInterface { return $promise->then(function ($value) { return $value * 2; }); } function getPromisesFromSource(): PromisorInterface { return new EachPromise($items, [ 'fulfilled' => function ($value) { /* ... */ } ]); } ``` -------------------------------- ### GeneratorFn Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A callable that returns a `Generator` object, used by `Coroutine` to create promise-based async sequences. ```php $generatorFn = function () { $a = yield promise1(); $b = yield promise2($a); return $a . $b; }; $coroutine = new Coroutine($generatorFn); ``` -------------------------------- ### Chaining Tasks in a Queue Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/task-queue.md Shows how to add multiple tasks to a queue and how tasks can dynamically add more tasks. ```php $queue = Utils::queue(); $queue->add(function () { echo "Step 1\n"; }); $queue->add(function () { echo "Step 2\n"; }); $queue->add(function () use ($queue) { echo "Step 3\n"; // Can add more tasks before the queue is emptied $queue->add(function () { echo "Step 3b (added dynamically)\n"; }); }); $queue->run(); // Output: // Step 1 // Step 2 // Step 3 // Step 3b (added dynamically) ``` -------------------------------- ### OnEachRejected Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A side-effect callback invoked for each rejected promise in an iteration. Can be used to short-circuit the aggregate promise. ```php Each::of($promises, null, function ($reason, $index, $aggregate) { echo "Error at [$index]: $reason\n"; }); ``` -------------------------------- ### Promise Constructor and Methods Source: https://github.com/guzzle/promises/blob/2.5/README.md Demonstrates the creation of a Promise with optional wait and cancel functions, and outlines the available methods for promise manipulation. ```APIDOC ## Promise When creating a promise object, you can provide an optional `$waitFn` and `$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is expected to resolve the promise. `$cancelFn` is a function with no arguments that is expected to cancel the computation of a promise. It is invoked when the `cancel()` method of a promise is called. ```php use GuzzleHttp\Promise\Promise; $promise = new Promise( function () use (&$promise) { $promise->resolve('waited'); }, function () { // do something that will cancel the promise computation (e.g., close // a socket, cancel a database query, etc...) } ); assert('waited' === $promise->wait()); ``` A promise has the following methods: - `then(?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface` Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. If a handler is omitted, the original fulfillment value or rejection reason is forwarded. - `otherwise(callable $onRejected) : PromiseInterface` Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. - `wait($unwrap = true) : mixed` Synchronously waits on the promise to complete. `$unwrap` controls whether or not the value of the promise is returned for a fulfilled promise or if an exception is thrown if the promise is rejected. This is set to `true` by default. - `cancel()` Attempts to cancel the promise if possible. The promise being cancelled and the parent most ancestor that has not yet been resolved will also be cancelled. Any promises waiting on the cancelled promise to resolve will also be cancelled. - `getState() : string` Returns the state of the promise. One of `pending`, `fulfilled`, or `rejected`. - `resolve($value)` Fulfills the promise with the given `$value`. - `reject($reason)` Rejects the promise with the given `$reason`. ``` -------------------------------- ### OnEachFulfilled Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A side-effect callback invoked for each fulfilled promise in an iteration. Can be used to short-circuit the aggregate promise. ```php Each::of($promises, function ($value, $index, $aggregate) { echo "[$index] $value\n"; }); ``` -------------------------------- ### EachPromise vs. Each::ofLimit Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each-promise.md Illustrates the equivalence between using the static Each::ofLimit method and instantiating EachPromise with a concurrency limit. Use Each::ofLimit for controlled concurrency. ```php Each::ofLimit($promises, 5, $onFulfilled, $onRejected); new EachPromise($promises, [ 'concurrency' => 5, 'fulfilled' => $onFulfilled, 'rejected' => $onRejected, ])->promise(); ``` -------------------------------- ### EachPromise Configuration Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md Configuration array for the EachPromise constructor. All keys are optional, allowing customization of fulfillment/rejection callbacks and concurrency. ```php [ 'fulfilled' => callable|null, // onFulfilled callback 'rejected' => callable|null, // onRejected callback 'concurrency' => int|callable, // max concurrent promises ] ``` -------------------------------- ### CancelFn Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A callback invoked when `cancel()` is called on a pending promise. Expected to cancel the asynchronous operation. ```php $cancelFn = function () { echo "Cancelling operation"; }; $promise = new Promise(null, $cancelFn); $promise->cancel(); // Invokes $cancelFn ``` -------------------------------- ### Manually Execute Promise Callbacks Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/README.md Shows how to manually execute pending promise callbacks using Utils::queue()->run() after resolving a promise. ```php use GuzzleHttp\Promise\Utils; $promise = new Promise(); $promise->resolve('value'); $promise->then(function ($value) { echo $value; }); Utils::queue()->run(); // Execute callbacks ``` -------------------------------- ### Guzzle Promises File Structure Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/README.md Illustrates the directory structure and the purpose of key files within the Guzzle Promises library. Helps in understanding the project's organization and locating specific components. ```text src/ ├── PromiseInterface.php // Main promise interface ├── PromisorInterface.php // Deferred pattern interface ├── Promise.php // Primary promise class ├── FulfilledPromise.php // Pre-fulfilled optimization ├── RejectedPromise.php // Pre-rejected optimization ├── Coroutine.php // Generator-based promises ├── Create.php // Factory methods ├── Utils.php // Aggregation utilities ├── Each.php // Iteration utility ├── EachPromise.php // Each implementation ├── Is.php // State inspection ├── TaskQueue.php // Task queue implementation ├── TaskQueueInterface.php // Queue interface ├── RejectionException.php // Exception class ├── AggregateException.php // Aggregate exception └── CancellationException.php // Cancellation exception ``` -------------------------------- ### Get Promise from PromisorInterface Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/interfaces.md Implementations of PromisorInterface return a promise managed by the object. This is useful for deferred or lazy promise creation. ```php public function promise(): PromiseInterface; ``` -------------------------------- ### Iterative Promise Chaining in PHP Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/README.md Demonstrates how to create long promise chains that resolve iteratively, maintaining a constant stack size. Useful for scenarios requiring deep asynchronous operations without stack overflow. ```php $p = $parent; for ($i = 0; $i < 10000; $i++) { $p = $p->then(function ($v) { return $v + 1; }); } $parent->resolve(0); $p->wait(); // Returns 10000, constant stack size ``` -------------------------------- ### Running the Guzzle Promise Task Queue Source: https://github.com/guzzle/promises/blob/2.5/README.md Shows how to obtain and manually run the global task queue for Guzzle promises. This is essential for resolving promises, especially when waiting synchronously or integrating with an event loop. ```php // Get the global task queue $queue = GuzzleHttp\Promise\Utils::queue(); $queue->run(); ``` -------------------------------- ### PromiseInterface Methods Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/MANIFEST.md Documentation for the core methods available on any Promise object. ```APIDOC ## then ### Description Attaches callbacks for the resolution and rejection of the promise. ### Method `then(callable $onFulfilled = null, callable $onRejected = null): PromiseInterface` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## otherwise ### Description Attaches a callback for the rejection of the promise. ### Method `otherwise(callable $onRejected): PromiseInterface` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## wait ### Description Waits for the promise to settle and returns its value or throws its exception. ### Method `wait(callable $onFulfilled = null, callable $onRejected = null): mixed` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## resolve ### Description Resolves the promise with a given value. ### Method `resolve(mixed $value): PromiseInterface` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## reject ### Description Rejects the promise with a given reason. ### Method `reject(mixed $reason): PromiseInterface` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## cancel ### Description Cancels the promise, preventing it from settling. ### Method `cancel(): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## getState ### Description Returns the current state of the promise. ### Method `getState(): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Asynchronous Promise Execution Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Illustrates creating promises and chaining handlers asynchronously. Resolution and handler execution are queued and run explicitly using `Utils::queue()->run()`. ```php $p = new Promise(); $p->then(fn($v) => $v * 2) // Creates new Promise, queues handler ->then(fn($v) => $v + 5); // Creates new Promise, queues handler $p->resolve(10); // Queues callback execution Utils::queue()->run(); // Executes queued handlers ``` -------------------------------- ### Iterating Over Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Demonstrates iterating over a collection of promises with different concurrency options. ```php Each::of($promises, $onFulfilled, $onRejected) ``` ```php Each::ofLimit($promises, 5, $onFulfilled, $onRejected) ``` ```php Each::ofLimitAll($promises, 5, $onFulfilled) ``` -------------------------------- ### Managing the Promise Queue Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Utilities for accessing and running the default or a custom task queue. ```php Utils::queue()->run() ``` ```php Utils::queue($customQueue) ``` ```php Utils::task(callable) ``` -------------------------------- ### OnRejected Callback Example Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/types.md A callback invoked when a promise is rejected. The return value becomes the resolution value for the returned promise. If a promise is returned, it is chained. ```php $onRejected = function ($reason) { return "Handled error: " . $reason; }; $promise->then(null, $onRejected); ``` -------------------------------- ### queue Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/utils.md Gets or sets the global task queue instance used for promise resolution. The same queue instance is used throughout the application for all promise operations. ```APIDOC ## queue ### Description Gets or sets the global task queue instance used for promise resolution. The same queue instance is used throughout the application for all promise operations. ### Method `public static function queue(?TaskQueueInterface $assign = null): TaskQueueInterface` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **$assign** (`TaskQueueInterface`|`null`) - Optional - If provided, replaces the global task queue with this instance. ### Return `TaskQueueInterface` - The current (or newly assigned) global task queue. ### Request Example ```php use GuzzleHttp\Promise\Utils; // Get the default queue $queue = Utils::queue(); // Replace with a custom queue $customQueue = new TaskQueue(false); Utils::queue($customQueue); // In an event loop while ($eventLoop->isRunning()) { Utils::queue()->run(); } ``` ``` -------------------------------- ### Catching AggregateException Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/errors.md Demonstrates how to catch an AggregateException and access individual rejection reasons using getReason(). ```php use GuzzleHttp\Promise\AggregateException; use GuzzleHttp\Promise\Utils; $promises = [ new RejectedPromise('error 1'), new RejectedPromise('error 2'), ]; Utils::some(2, $promises)->then( null, function ($reason) { if ($reason instanceof AggregateException) { $reasons = $reason->getReason(); // ['error 1', 'error 2'] foreach ($reasons as $r) { echo "Rejection: $r\n"; } } } ); ``` -------------------------------- ### Disable TaskQueue Shutdown Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/task-queue.md Disable automatic execution of remaining tasks at PHP shutdown. This must be called if tasks will be manually executed, for example, within an event loop. ```php use GuzzleHttp\Promise\TaskQueue; $queue = new TaskQueue(true); $queue->disableShutdown(); // Tasks must now be manually run in your event loop while ($eventLoop->isRunning()) { $queue->run(); // Actual event loop tick } ``` -------------------------------- ### Run Task Queue Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/task-queue.md Execute all pending tasks in the queue in FIFO order until it is empty. Each task is removed from the queue before execution. ```php $queue = new TaskQueue(); for ($i = 0; $i < 5; $i++) { $queue->add(function () use ($i) { echo "Task $i\n"; }); } $queue->run(); // Executes all 5 tasks in order ``` -------------------------------- ### Get Aggregate Promise Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each-promise.md Returns the aggregate promise that is fulfilled when all items have been processed. The promise is initially pending and becomes fulfilled (with null value) when iteration completes or rejected if halted early. ```php use GuzzleHttp\Promise\EachPromise; $each = new EachPromise( [promise1(), promise2(), promise3()], [ 'fulfilled' => function ($value, $index, $aggregate) { if ($value === 'stop') { $aggregate->resolve(null); // Stop early } } ] ); $aggregate = $each->promise(); $aggregate->then( function () { echo "Iteration complete\n"; }, function ($reason) { echo "Iteration failed: $reason\n"; } ); ``` -------------------------------- ### Check Promise State (Pending, Fulfilled) Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/is.md Demonstrates how to check if a promise is pending or fulfilled using Is::pending() and Is::fulfilled(). ```php use GuzzleHttp\Promise\Is; use GuzzleHttp\Promise\Promise; $promise = new Promise(); if (Is::pending($promise)) { echo "Promise is still pending\n"; } $promise->resolve('value'); if (Is::fulfilled($promise)) { echo "Promise is fulfilled\n"; } ``` -------------------------------- ### Get or Set Global Task Queue Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/utils.md Retrieves the current global task queue or sets a new one. Useful for managing promise resolution across an application or within an event loop. ```php use GuzzleHttp\Promise\Utils; // Get the default queue $queue = Utils::queue(); // Replace with a custom queue $customQueue = new TaskQueue(false); Utils::queue($customQueue); // In an event loop while ($eventLoop->isRunning()) { Utils::queue()->run(); } ``` -------------------------------- ### Create and Resolve a Promise Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/README.md Instantiate a new Promise and resolve it with a value or reason. Use the `then` method to attach callbacks for fulfillment and rejection. ```php use GuzzleHttp\Promise\Promise; $promise = new Promise(); $promise->then( function ($value) { echo "Fulfilled: " . $value; }, function ($reason) { echo "Rejected: " . $reason; } ); $promise->resolve('success'); ``` -------------------------------- ### Race Promises with Utils::some Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/utils.md Utilize `Utils::some` to get results from the first N promises that fulfill. This is useful when you need a result quickly from multiple sources and don't need all of them to complete. The second argument specifies how many promises should fulfill before the promise returned by `Utils::some` resolves. ```php use GuzzleHttp\Promise\Utils; $promises = [ fetchFromSource1(), fetchFromSource2(), fetchFromSource3(), ]; // First 2 sources to complete wins Utils::some(2, $promises)->then( function ($results) { echo "Got 2 responses: " . json_encode($results); }, function ($exception) { echo "Not enough responses: " . $exception->getMessage(); } ); ``` -------------------------------- ### Chaining Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Shows how to chain asynchronous operations using promises. ```php $promise->then($onFulfilled, $onRejected) ``` ```php $promise->otherwise($onRejected) ``` ```php Coroutine::of(function () { yield $promise; }) ``` -------------------------------- ### Wait for Rejection with wait() Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/rejected-promise.md Waits for the promise to settle. By default, it throws the rejection reason as an exception. If unwrap is false, it returns null. ```php $promise = new RejectedPromise('error message'); // With unwrap=true (default), an exception is thrown try { $promise->wait(); } catch (Throwable $e) { echo $e->getMessage(); // "The promise was rejected with reason: error message" } // With unwrap=false, no exception is thrown $promise->wait(false); // Returns null ``` -------------------------------- ### Creating and Using a RejectedPromise Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/rejected-promise.md Instantiates a RejectedPromise with an immediate error reason. Rejection callbacks attached via then() are invoked synchronously. ```php use GuzzleHttp\Promise\RejectedPromise; $promise = new RejectedPromise('immediate error'); // Rejection callbacks are invoked immediately $promise->then(null, function ($reason) { echo $reason; // "immediate error" }); ``` -------------------------------- ### Handle Rejected Promises with Exceptions Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/README.md Demonstrates how unwrapped promises that reject throw the reason as an exception. Non-exception reasons are wrapped in a RejectionException. ```php use GuzzleHttp\Promise\RejectedPromise; // Unwrapped promises that reject throw the reason $promise = new RejectedPromise(new Exception('error')); $promise->wait(); // Throws Exception // Non-exception reasons are wrapped $promise = new RejectedPromise('string reason'); try { $promise->wait(); } catch (RejectionException $e) { echo $e->getReason(); // "string reason" } ``` -------------------------------- ### Pre-Fulfilled and Pre-Rejected Promises Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/README.md Create promises that are immediately fulfilled or rejected using `FulfilledPromise` and `RejectedPromise`. This is useful for providing default values or handling immediate errors. ```php use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Promise\RejectedPromise; $fulfilled = new FulfilledPromise('immediate value'); $rejected = new RejectedPromise('immediate error'); $fulfilled->then(function ($value) { echo $value; // "immediate value" }); $rejected->then(null, function ($reason) { echo $reason; // "immediate error" }); ``` -------------------------------- ### Looping in Coroutines Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/coroutine.md Demonstrates how to perform iterative asynchronous operations within a coroutine using a standard for loop. ```php use GuzzleHttp\Promise\Coroutine; Coroutine::of(function () { $results = []; for ($i = 0; $i < 10; $i++) { $item = yield fetchItem($i); $results[] = $item; } return $results; })->then(function ($_items) { echo "Fetched " . count($_items) . " items"; }); ``` -------------------------------- ### TaskQueue Methods Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Methods for managing a task queue, including adding tasks, running the queue, checking if it's empty, and disabling shutdown. ```APIDOC ## TaskQueue Methods ### `__construct(bool $withShutdown = true)` Initializes a new TaskQueue instance. ### `add(callable $task): void` Adds a callable task to the queue. ### `run(): void` Executes all tasks in the queue. ### `isEmpty(): bool` Checks if the task queue is empty. ### `disableShutdown(): void` Disables the shutdown behavior for the task queue. ``` -------------------------------- ### EachPromise Constructor Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each-promise.md Initializes a new EachPromise instance. It takes an iterable of promises or values and an optional configuration array for callbacks and concurrency. ```APIDOC ## `EachPromise` Constructor ### Description Initializes a new `EachPromise` instance. It takes an iterable of promises or values and an optional configuration array for callbacks and concurrency. ### Method `__construct(iterable $iterable, array $config = [])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **`$iterable`** (iterable) - Required - An iterable of promises or values to iterate over. - **`$config`** (array) - Optional - Configuration options. - **`fulfilled`** (callable|null) - Optional - Callback invoked for each fulfilled promise. Signature: `function($value, $index, PromiseInterface $aggregate)` - **`rejected`** (callable|null) - Optional - Callback invoked for each rejected promise. Signature: `function($reason, $index, PromiseInterface $aggregate)` - **`concurrency`** (int|callable|null) - Optional - Maximum number of promises to execute concurrently. Can be a callable that receives pending count and returns a limit. ### Request Example ```php use GuzzleHttp\Promise\EachPromise; $each = new EachPromise( [promise1(), promise2(), promise3()], [ 'fulfilled' => function ($value, $index) { echo "[$index] Success: $value\n"; }, 'rejected' => function ($reason, $index) { echo "[$index] Error: $reason\n"; }, 'concurrency' => 2, // Max 2 concurrent ] ); $promise = $each->promise(); $promise->then(function () { echo "All done\n"; }); ``` ### Response None directly from constructor. The constructor returns a `PromisorInterface` instance. ``` -------------------------------- ### Inspect Promise State in Callbacks Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/is.md Shows how to iterate through an array of promises and check if each one is settled, fulfilled, or rejected within a loop. ```php use GuzzleHttp\Promise\Is; $promises = [$p1, $p2, $p3]; foreach ($promises as $p) { if (Is::settled($p)) { if (Is::fulfilled($p)) { echo "Fulfilled: " . $p->wait() . "\n"; } else { echo "Rejected\n"; } } } ``` -------------------------------- ### Global Queue Management Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/interfaces.md Demonstrates how to retrieve the default task queue or set a custom one using Guzzle's Utils::queue() method. This allows for centralized control over promise task execution. ```php use GuzzleHttp\Promise\Utils; use GuzzleHttp\Promise\TaskQueue; // Get default queue $queue = Utils::queue(); // Set custom queue $custom = new TaskQueue(false); Utils::queue($custom); ``` -------------------------------- ### Handling Promise Rejection with String in PHP Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/errors.md Illustrates a promise being rejected with a string. The RejectionException will wrap the string, and getReason() will return it. ```php $promise = new RejectedPromise('error message'); try { $promise->wait(); } catch (RejectionException $e) { // getMessage(): "The promise was rejected with reason: error message" // getReason(): "error message" } ``` -------------------------------- ### Instantiate TaskQueue Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/task-queue.md Instantiate TaskQueue with or without automatic shutdown execution. The default behavior includes registering a PHP shutdown function to run the queue on script exit. ```php use GuzzleHttp\Promise\TaskQueue; // Default: with automatic shutdown execution $queue = new TaskQueue(); // Without automatic shutdown (manual execution required) $queue = new TaskQueue(false); ``` -------------------------------- ### Short-Circuiting Iteration Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/each.md Demonstrates how to short-circuit the iteration process by resolving the aggregate promise when a specific condition is met. ```php Each::of($promises, function ($value, $index, $aggregate) { if ($value === 'stop') { $aggregate->resolve(null); // Stop processing } } ); ``` -------------------------------- ### Create Promise from Task Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/utils.md Adds a callable task to the global queue and returns a promise that resolves with the task's result. Ensure the queue is run to execute the task. ```php use GuzzleHttp\Promise\Utils; $promise = Utils::task(function () { return 'task result'; }); $promise->then(function ($result) { echo $result; // "task result" }); Utils::queue()->run(); // Execute the task ``` -------------------------------- ### Fallback with Utils::any Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/utils.md Employ `Utils::any` to resolve with the value of the first promise that fulfills, even if others reject. This is ideal for implementing fallback mechanisms where a primary operation might fail, but a secondary or default option is available. ```php use GuzzleHttp\Promise\Utils; $promises = [ new RejectedPromise('primary error'), new RejectedPromise('secondary error'), new FulfilledPromise('fallback value'), ]; Utils::any($promises)->then(function ($value) { echo "Using: " . $value; // "Using: fallback value" }); ``` -------------------------------- ### Create Promise Factory Methods Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Factory methods for creating promises. Use `promiseFor` to wrap a value, `rejectionFor` to create a rejected promise, `exceptionFor` to create a throwable, and `iterFor` to create an iterator. ```php Create::promiseFor($value): PromiseInterface Create::rejectionFor($reason): PromiseInterface Create::exceptionFor($reason): \Throwable Create::iterFor($value): \Iterator ``` -------------------------------- ### run Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/task-queue.md Executes all pending tasks in the queue in FIFO order until the queue is empty. Each task is removed from the queue before execution. ```APIDOC ## run ### Description Executes all pending tasks in the queue in FIFO order until the queue is empty. Each task is removed from the queue before execution. ### Method ```php run(): void ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $queue = new TaskQueue(); for ($i = 0; $i < 5; $i++) { $queue->add(function () use ($i) { echo "Task $i\n"; }); } $queue->run(); // Executes all 5 tasks in order ``` ### Response #### Success Response (void) This method does not return a value. ``` -------------------------------- ### Create a Rejected Promise Source: https://github.com/guzzle/promises/blob/2.5/README.md Create a RejectedPromise instance to represent a promise that has been rejected. Rejection callbacks are invoked immediately. ```php use GuzzleHttp\Promise\RejectedPromise; $promise = new RejectedPromise('Error'); // Rejected callbacks are immediately invoked. $promise->then(null, function ($reason) { echo $reason; }); ``` -------------------------------- ### Queue in Synchronous Wait Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-reference/task-queue.md Illustrates using a promise's `wait()` method to synchronously execute tasks within the queue. ```php use GuzzleHttp\Promise\Promise; $promise = new Promise(function () use (&$promise) { // Wait function echo "Wait function called\n"; $promise->resolve('result'); }); echo "Calling wait...\n"; $result = $promise->wait(); echo "Result: $result\n"; // Output: // Calling wait... // Wait function called // Result: result ``` -------------------------------- ### EachPromise Configuration Type Alias Source: https://github.com/guzzle/promises/blob/2.5/_autodocs/api-index.md Defines the configuration options for EachPromise. ```php [ 'fulfilled' => ?callable, 'rejected' => ?callable, 'concurrency' => ?int|callable, ] ```