[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-8238":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":20,"hasPages":20,"topics":22,"createdAt":10,"pushedAt":10,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":16,"starSnapshotCount":16,"syncStatus":26,"lastSyncTime":27,"discoverSource":28},8238,"promises","guzzle\u002Fpromises","guzzle","Promises\u002FA+ library for PHP with synchronous support","",null,"PHP",7719,126,33,1,0,5,37.31,"MIT License",false,"2.3",[],"2026-06-12 02:01:51","# Guzzle Promises\n\n[Promises\u002FA+](https:\u002F\u002Fpromisesaplus.com\u002F) implementation that handles promise\nchaining and resolution iteratively, allowing for \"infinite\" promise chaining\nwhile keeping the stack size constant. Read [this blog post](https:\u002F\u002Fblog.domenic.me\u002Fyoure-missing-the-point-of-promises\u002F)\nfor a general introduction to promises.\n\n- [Features](#features)\n- [Quick start](#quick-start)\n- [Synchronous wait](#synchronous-wait)\n- [Cancellation](#cancellation)\n- [API](#api)\n  - [Promise](#promise)\n  - [FulfilledPromise](#fulfilledpromise)\n  - [RejectedPromise](#rejectedpromise)\n- [Promise interop](#promise-interop)\n- [Implementation notes](#implementation-notes)\n\n\n## Features\n\n- [Promises\u002FA+](https:\u002F\u002Fpromisesaplus.com\u002F) implementation.\n- Promise resolution and chaining is handled iteratively, allowing for\n  \"infinite\" promise chaining.\n- Promises have a synchronous `wait` method.\n- Promises can be cancelled.\n- Works with any object that has a `then` function.\n- C# style async\u002Fawait coroutine promises using\n  `GuzzleHttp\\Promise\\Coroutine::of()`.\n\n\n## Installation\n\n```shell\ncomposer require guzzlehttp\u002Fpromises\n```\n\n\n## Version Guidance\n\n| Version | Status              | PHP Version  |\n|---------|---------------------|--------------|\n| 1.x     | Security fixes only | >=5.5,\u003C8.3   |\n| 2.x     | Latest              | >=7.2.5,\u003C8.6 |\n\n\n## Quick Start\n\nA *promise* represents the eventual result of an asynchronous operation. The\nprimary way of interacting with a promise is through its `then` method, which\nregisters callbacks to receive either a promise's eventual value or the reason\nwhy the promise cannot be fulfilled.\n\n### Callbacks\n\nCallbacks are registered with the `then` method by providing an optional \n`$onFulfilled` followed by an optional `$onRejected` function.\n\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\n\n$promise = new Promise();\n$promise->then(\n    \u002F\u002F $onFulfilled\n    function ($value) {\n        echo 'The promise was fulfilled.';\n    },\n    \u002F\u002F $onRejected\n    function ($reason) {\n        echo 'The promise was rejected.';\n    }\n);\n```\n\n*Resolving* a promise means that you either fulfill a promise with a *value* or\nreject a promise with a *reason*. Resolving a promise triggers callbacks\nregistered with the promise's `then` method. These callbacks are triggered\nonly once and in the order in which they were added.\n\n### Resolving a Promise\n\nPromises are fulfilled using the `resolve($value)` method. Resolving a promise\nwith any value other than a `GuzzleHttp\\Promise\\RejectedPromise` will trigger\nall of the onFulfilled callbacks (resolving a promise with a rejected promise\nwill reject the promise and trigger the `$onRejected` callbacks).\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\n\n$promise = new Promise();\n$promise\n    ->then(function ($value) {\n        \u002F\u002F Return a value and don't break the chain\n        return \"Hello, \" . $value;\n    })\n    \u002F\u002F This then is executed after the first then and receives the value\n    \u002F\u002F returned from the first then.\n    ->then(function ($value) {\n        echo $value;\n    });\n\n\u002F\u002F Resolving the promise triggers the $onFulfilled callbacks and outputs\n\u002F\u002F \"Hello, reader.\"\n$promise->resolve('reader.');\n```\n\n### Promise Forwarding\n\nPromises can be chained one after the other. Each then in the chain is a new\npromise. The return value of a promise is what's forwarded to the next\npromise in the chain. Returning a promise in a `then` callback will cause the\nsubsequent promises in the chain to only be fulfilled when the returned promise\nhas been fulfilled. The next promise in the chain will be invoked with the\nresolved value of the promise.\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\n\n$promise = new Promise();\n$nextPromise = new Promise();\n\n$promise\n    ->then(function ($value) use ($nextPromise) {\n        echo $value;\n        return $nextPromise;\n    })\n    ->then(function ($value) {\n        echo $value;\n    });\n\n\u002F\u002F Triggers the first callback and outputs \"A\"\n$promise->resolve('A');\n\u002F\u002F Triggers the second callback and outputs \"B\"\n$nextPromise->resolve('B');\n```\n\n### Promise Rejection\n\nWhen a promise is rejected, the `$onRejected` callbacks are invoked with the\nrejection reason.\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\n\n$promise = new Promise();\n$promise->then(null, function ($reason) {\n    echo $reason;\n});\n\n$promise->reject('Error!');\n\u002F\u002F Outputs \"Error!\"\n```\n\n### Rejection Forwarding\n\nIf an exception is thrown in an `$onRejected` callback, subsequent\n`$onRejected` callbacks are invoked with the thrown exception as the reason.\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\n\n$promise = new Promise();\n$promise->then(null, function ($reason) {\n    throw new Exception($reason);\n})->then(null, function ($reason) {\n    assert($reason->getMessage() === 'Error!');\n});\n\n$promise->reject('Error!');\n```\n\nYou can also forward a rejection down the promise chain by returning a\n`GuzzleHttp\\Promise\\RejectedPromise` in either an `$onFulfilled` or\n`$onRejected` callback.\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\nuse GuzzleHttp\\Promise\\RejectedPromise;\n\n$promise = new Promise();\n$promise->then(null, function ($reason) {\n    return new RejectedPromise($reason);\n})->then(null, function ($reason) {\n    assert($reason === 'Error!');\n});\n\n$promise->reject('Error!');\n```\n\nIf an exception is not thrown in a `$onRejected` callback and the callback\ndoes not return a rejected promise, downstream `$onFulfilled` callbacks are\ninvoked using the value returned from the `$onRejected` callback.\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\n\n$promise = new Promise();\n$promise\n    ->then(null, function ($reason) {\n        return \"It's ok\";\n    })\n    ->then(function ($value) {\n        assert($value === \"It's ok\");\n    });\n\n$promise->reject('Error!');\n```\n\n\n## Synchronous Wait\n\nYou can synchronously force promises to complete using a promise's `wait`\nmethod. When creating a promise, you can provide a wait function that is used\nto synchronously force a promise to complete. When a wait function is invoked\nit is expected to deliver a value to the promise or reject the promise. If the\nwait function does not deliver a value, then an exception is thrown. The wait\nfunction provided to a promise constructor is invoked when the `wait` function\nof the promise is called.\n\n```php\n$promise = new Promise(function () use (&$promise) {\n    $promise->resolve('foo');\n});\n\n\u002F\u002F Calling wait will return the value of the promise.\necho $promise->wait(); \u002F\u002F outputs \"foo\"\n```\n\nIf an exception is encountered while invoking the wait function of a promise,\nthe promise is rejected with the exception and the exception is thrown.\n\n```php\n$promise = new Promise(function () use (&$promise) {\n    throw new Exception('foo');\n});\n\n$promise->wait(); \u002F\u002F throws the exception.\n```\n\nCalling `wait` on a promise that has been fulfilled will not trigger the wait\nfunction. It will simply return the previously resolved value.\n\n```php\n$promise = new Promise(function () { die('this is not called!'); });\n$promise->resolve('foo');\necho $promise->wait(); \u002F\u002F outputs \"foo\"\n```\n\nCalling `wait` on a promise that has been rejected will throw an exception. If\nthe rejection reason is an instance of `\\Exception` the reason is thrown.\nOtherwise, a `GuzzleHttp\\Promise\\RejectionException` is thrown and the reason\ncan be obtained by calling the `getReason` method of the exception.\n\n```php\n$promise = new Promise();\n$promise->reject('foo');\n$promise->wait();\n```\n\n> PHP Fatal error:  Uncaught exception 'GuzzleHttp\\Promise\\RejectionException' with message 'The promise was rejected with value: foo'\n\n### Unwrapping a Promise\n\nWhen synchronously waiting on a promise, you are joining the state of the\npromise into the current state of execution (i.e., return the value of the\npromise if it was fulfilled or throw an exception if it was rejected). This is\ncalled \"unwrapping\" the promise. Waiting on a promise will by default unwrap\nthe promise state.\n\nYou can force a promise to resolve and *not* unwrap the state of the promise\nby passing `false` to the first argument of the `wait` function:\n\n```php\n$promise = new Promise();\n$promise->reject('foo');\n\u002F\u002F This will not throw an exception. It simply ensures the promise has\n\u002F\u002F been resolved.\n$promise->wait(false);\n```\n\nWhen unwrapping a promise, the resolved value of the promise will be waited\nupon until the unwrapped value is not a promise. This means that if you resolve\npromise A with a promise B and unwrap promise A, the value returned by the\nwait function will be the value delivered to promise B.\n\n**Note**: when you do not unwrap the promise, no value is returned.\n\n\n## Cancellation\n\nYou can cancel a promise that has not yet been fulfilled using the `cancel()`\nmethod of a promise. When creating a promise you can provide an optional\ncancel function that when invoked cancels the action of computing a resolution\nof the promise.\n\n\n## API\n\n### Promise\n\nWhen creating a promise object, you can provide an optional `$waitFn` and\n`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is\nexpected to resolve the promise. `$cancelFn` is a function with no arguments\nthat is expected to cancel the computation of a promise. It is invoked when the\n`cancel()` method of a promise is called.\n\n```php\nuse GuzzleHttp\\Promise\\Promise;\n\n$promise = new Promise(\n    function () use (&$promise) {\n        $promise->resolve('waited');\n    },\n    function () {\n        \u002F\u002F do something that will cancel the promise computation (e.g., close\n        \u002F\u002F a socket, cancel a database query, etc...)\n    }\n);\n\nassert('waited' === $promise->wait());\n```\n\nA promise has the following methods:\n\n- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface`\n  \n  Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler.\n\n- `otherwise(callable $onRejected) : PromiseInterface`\n  \n  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.\n\n- `wait($unwrap = true) : mixed`\n\n  Synchronously waits on the promise to complete.\n  \n  `$unwrap` controls whether or not the value of the promise is returned for a\n  fulfilled promise or if an exception is thrown if the promise is rejected.\n  This is set to `true` by default.\n\n- `cancel()`\n\n  Attempts to cancel the promise if possible. The promise being cancelled and\n  the parent most ancestor that has not yet been resolved will also be\n  cancelled. Any promises waiting on the cancelled promise to resolve will also\n  be cancelled.\n\n- `getState() : string`\n\n  Returns the state of the promise. One of `pending`, `fulfilled`, or\n  `rejected`.\n\n- `resolve($value)`\n\n  Fulfills the promise with the given `$value`.\n\n- `reject($reason)`\n\n  Rejects the promise with the given `$reason`.\n\n\n### FulfilledPromise\n\nA fulfilled promise can be created to represent a promise that has been\nfulfilled.\n\n```php\nuse GuzzleHttp\\Promise\\FulfilledPromise;\n\n$promise = new FulfilledPromise('value');\n\n\u002F\u002F Fulfilled callbacks are immediately invoked.\n$promise->then(function ($value) {\n    echo $value;\n});\n```\n\n\n### RejectedPromise\n\nA rejected promise can be created to represent a promise that has been\nrejected.\n\n```php\nuse GuzzleHttp\\Promise\\RejectedPromise;\n\n$promise = new RejectedPromise('Error');\n\n\u002F\u002F Rejected callbacks are immediately invoked.\n$promise->then(null, function ($reason) {\n    echo $reason;\n});\n```\n\n\n## Promise Interoperability\n\nThis library works with foreign promises that have a `then` method. This means\nyou can use Guzzle promises with [React promises](https:\u002F\u002Fgithub.com\u002Freactphp\u002Fpromise)\nfor example. When a foreign promise is returned inside of a then method\ncallback, promise resolution will occur recursively.\n\n```php\n\u002F\u002F Create a React promise\n$deferred = new React\\Promise\\Deferred();\n$reactPromise = $deferred->promise();\n\n\u002F\u002F Create a Guzzle promise that is fulfilled with a React promise.\n$guzzlePromise = new GuzzleHttp\\Promise\\Promise();\n$guzzlePromise->then(function ($value) use ($reactPromise) {\n    \u002F\u002F Do something something with the value...\n    \u002F\u002F Return the React promise\n    return $reactPromise;\n});\n```\n\nPlease note that wait and cancel chaining is no longer possible when forwarding\na foreign promise. You will need to wrap a third-party promise with a Guzzle\npromise in order to utilize wait and cancel functions with foreign promises.\n\n\n### Event Loop Integration\n\nIn order to keep the stack size constant, Guzzle promises are resolved\nasynchronously using a task queue. When waiting on promises synchronously, the\ntask queue will be automatically run to ensure that the blocking promise and\nany forwarded promises are resolved. When using promises asynchronously in an\nevent loop, you will need to run the task queue on each tick of the loop. If\nyou do not run the task queue, then promises will not be resolved.\n\nYou can run the task queue using the `run()` method of the global task queue\ninstance.\n\n```php\n\u002F\u002F Get the global task queue\n$queue = GuzzleHttp\\Promise\\Utils::queue();\n$queue->run();\n```\n\nFor example, you could use Guzzle promises with React using a periodic timer:\n\n```php\n$loop = React\\EventLoop\\Factory::create();\n$loop->addPeriodicTimer(0, [$queue, 'run']);\n```\n\n\n## Implementation Notes\n\n### Promise Resolution and Chaining is Handled Iteratively\n\nBy shuffling pending handlers from one owner to another, promises are\nresolved iteratively, allowing for \"infinite\" then chaining.\n\n```php\n\u003C?php\nrequire 'vendor\u002Fautoload.php';\n\nuse GuzzleHttp\\Promise\\Promise;\n\n$parent = new Promise();\n$p = $parent;\n\nfor ($i = 0; $i \u003C 1000; $i++) {\n    $p = $p->then(function ($v) {\n        \u002F\u002F The stack size remains constant (a good thing)\n        echo xdebug_get_stack_depth() . ', ';\n        return $v + 1;\n    });\n}\n\n$parent->resolve(0);\nvar_dump($p->wait()); \u002F\u002F int(1000)\n\n```\n\nWhen a promise is fulfilled or rejected with a non-promise value, the promise\nthen takes ownership of the handlers of each child promise and delivers values\ndown the chain without using recursion.\n\nWhen a promise is resolved with another promise, the original promise transfers\nall of its pending handlers to the new promise. When the new promise is\neventually resolved, all of the pending handlers are delivered the forwarded\nvalue.\n\n### A Promise is the Deferred\n\nSome promise libraries implement promises using a deferred object to represent\na computation and a promise object to represent the delivery of the result of\nthe computation. This is a nice separation of computation and delivery because\nconsumers of the promise cannot modify the value that will be eventually\ndelivered.\n\nOne side effect of being able to implement promise resolution and chaining\niteratively is that you need to be able for one promise to reach into the state\nof another promise to shuffle around ownership of handlers. In order to achieve\nthis without making the handlers of a promise publicly mutable, a promise is\nalso the deferred value, allowing promises of the same parent class to reach\ninto and modify the private properties of promises of the same type. While this\ndoes allow consumers of the value to modify the resolution or rejection of the\ndeferred, it is a small price to pay for keeping the stack size constant.\n\n```php\n$promise = new Promise();\n$promise->then(function ($value) { echo $value; });\n\u002F\u002F The promise is the deferred value, so you can deliver a value to it.\n$promise->resolve('foo');\n\u002F\u002F prints \"foo\"\n```\n\n\n## Upgrading from Function API\n\nA static API was first introduced in 1.4.0, in order to mitigate problems with\nfunctions conflicting between global and local copies of the package. The\nfunction API was removed in 2.0.0. A migration table has been provided here for\nyour convenience:\n\n| Original Function | Replacement Method |\n|----------------|----------------|\n| `queue` | `Utils::queue` |\n| `task` | `Utils::task` |\n| `promise_for` | `Create::promiseFor` |\n| `rejection_for` | `Create::rejectionFor` |\n| `exception_for` | `Create::exceptionFor` |\n| `iter_for` | `Create::iterFor` |\n| `inspect` | `Utils::inspect` |\n| `inspect_all` | `Utils::inspectAll` |\n| `unwrap` | `Utils::unwrap` |\n| `all` | `Utils::all` |\n| `some` | `Utils::some` |\n| `any` | `Utils::any` |\n| `settle` | `Utils::settle` |\n| `each` | `Each::of` |\n| `each_limit` | `Each::ofLimit` |\n| `each_limit_all` | `Each::ofLimitAll` |\n| `!is_fulfilled` | `Is::pending` |\n| `is_fulfilled` | `Is::fulfilled` |\n| `is_rejected` | `Is::rejected` |\n| `is_settled` | `Is::settled` |\n| `coroutine` | `Coroutine::of` |\n\n\n## Security\n\nIf you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https:\u002F\u002Fgithub.com\u002Fguzzle\u002Fpromises\u002Fsecurity\u002Fpolicy) for more information.\n\n\n## License\n\nGuzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.\n\n\n## For Enterprise\n\nAvailable as part of the Tidelift Subscription\n\nThe maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https:\u002F\u002Ftidelift.com\u002Fsubscription\u002Fpkg\u002Fpackagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)\n","guzzle\u002Fpromises 是一个符合 Promises\u002FA+ 规范的 PHP 库，支持同步操作。该项目的核心功能包括迭代处理 promise 链接和解析，从而支持“无限”的 promise 链接而不会增加调用栈大小，并且提供了一个同步 `wait` 方法来等待 promise 完成。此外，它还支持 promise 的取消以及与任何具有 `then` 函数的对象兼容。guzzle\u002Fpromises 适用于需要异步编程但又希望保持代码简洁、易于维护的应用场景，如网络请求、数据处理等。通过 Composer 可轻松集成到现有 PHP 项目中。",2,"2026-06-11 03:16:57","top_language"]