BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / push / vendor / guzzlehttp / promises / README.md

README.md

README.md 16.5 KiB Download Raw

Guzzle Promises

Promises/A+ implementation that handles promise chaining and resolution iteratively, allowing for "infinite" promise chaining while keeping the stack size constant. Read this blog post for a general introduction to promises.

Features

  • Promises/A+ implementation.
  • Promise resolution and chaining is handled iteratively, allowing for

"infinite" promise chaining.

  • Promises have a synchronous wait method.
  • Promises can be cancelled.
  • Works with any object that has a then function.
  • C# style async/await coroutine promises using

GuzzleHttp\Promise\Coroutine::of().

Installation

composer require guzzlehttp/promises

Version Guidance

VersionStatusPHP Version
1.xSecurity fixes only>=5.5,<8.3
2.xLatest>=7.2.5,<8.7

Quick Start

A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled.

Callbacks

Callbacks are registered with the then method by providing an optional $onFulfilled followed by an optional $onRejected function.

use GuzzleHttp\Promise\Promise;

$promise = new Promise();
$promise->then(
    // $onFulfilled
    function ($value) {
        echo 'The promise was fulfilled.';
    },
    // $onRejected
    function ($reason) {
        echo 'The promise was rejected.';
    }
);

Resolving a promise means that you either fulfill a promise with a value or reject a promise with a reason. Resolving a promise triggers callbacks registered with the promise's then method. These callbacks are triggered only once and in the order in which they were added.

Resolving a Promise

Promises are fulfilled using the resolve($value) method. Resolving a promise with any value other than a GuzzleHttp\Promise\RejectedPromise will trigger all of the onFulfilled callbacks (resolving a promise with a rejected promise will reject the promise and trigger the $onRejected callbacks).

use GuzzleHttp\Promise\Promise;

$promise = new Promise();
$promise
    ->then(function ($value) {
        // Return a value and don't break the chain
        return "Hello, " . $value;
    })
    // This then is executed after the first then and receives the value
    // returned from the first then.
    ->then(function ($value) {
        echo $value;
    });

// Resolving the promise triggers the $onFulfilled callbacks and outputs
// "Hello, reader."
$promise->resolve('reader.');

Promise Forwarding

Promises can be chained one after the other. Each then in the chain is a new promise. The return value of a promise is what's forwarded to the next promise in the chain. Returning a promise in a then callback will cause the subsequent promises in the chain to only be fulfilled when the returned promise has been fulfilled. The next promise in the chain will be invoked with the resolved value of the promise.

use GuzzleHttp\Promise\Promise;

$promise = new Promise();
$nextPromise = new Promise();

$promise
    ->then(function ($value) use ($nextPromise) {
        echo $value;
        return $nextPromise;
    })
    ->then(function ($value) {
        echo $value;
    });

// Triggers the first callback and outputs "A"
$promise->resolve('A');
// Triggers the second callback and outputs "B"
$nextPromise->resolve('B');

Promise Rejection

When a promise is rejected, the $onRejected callbacks are invoked with the rejection reason.

use GuzzleHttp\Promise\Promise;

$promise = new Promise();
$promise->then(null, function ($reason) {
    echo $reason;
});

$promise->reject('Error!');
// Outputs "Error!"

Rejection Forwarding

If an exception is thrown in an $onRejected callback, subsequent $onRejected callbacks are invoked with the thrown exception as the reason.

use GuzzleHttp\Promise\Promise;

$promise = new Promise();
$promise->then(null, function ($reason) {
    throw new Exception($reason);
})->then(null, function ($reason) {
    assert($reason->getMessage() === 'Error!');
});

$promise->reject('Error!');

You can also forward a rejection down the promise chain by returning a GuzzleHttp\Promise\RejectedPromise in either an $onFulfilled or $onRejected callback.

use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\RejectedPromise;

$promise = new Promise();
$promise->then(null, function ($reason) {
    return new RejectedPromise($reason);
})->then(null, function ($reason) {
    assert($reason === 'Error!');
});

$promise->reject('Error!');

If an exception is not thrown in a $onRejected callback and the callback does not return a rejected promise, downstream $onFulfilled callbacks are invoked using the value returned from the $onRejected callback.

use GuzzleHttp\Promise\Promise;

$promise = new Promise();
$promise
    ->then(null, function ($reason) {
        return "It's ok";
    })
    ->then(function ($value) {
        assert($value === "It's ok");
    });

$promise->reject('Error!');

Synchronous Wait

You can synchronously force promises to complete using a promise's wait method. When creating a promise, you can provide a wait function that is used to synchronously force a promise to complete. When a wait function is invoked it is expected to deliver a value to the promise or reject the promise. If the wait function does not deliver a value, then an exception is thrown. The wait function provided to a promise constructor is invoked when the wait function of the promise is called.

$promise = new Promise(function () use (&$promise) {
    $promise->resolve('foo');
});

// Calling wait will return the value of the promise.
echo $promise->wait(); // outputs "foo"

If a throwable is encountered while invoking the wait function of a promise, the promise is rejected with the throwable and the throwable is thrown.

$promise = new Promise(function () use (&$promise) {
    throw new Exception('foo');
});

$promise->wait(); // throws the exception.

Calling wait on a promise that has been fulfilled will not trigger the wait function. It will simply return the previously resolved value.

$promise = new Promise(function () { die('this is not called!'); });
$promise->resolve('foo');
echo $promise->wait(); // outputs "foo"

Calling wait on a promise that has been rejected will throw. If the rejection reason is an instance of \Throwable the reason is thrown. Otherwise, a GuzzleHttp\Promise\RejectionException is thrown and the reason can be obtained by calling the getReason method of the exception.

$promise = new Promise();
$promise->reject('foo');
$promise->wait();

> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo'

Unwrapping a Promise

When synchronously waiting on a promise, you are joining the state of the promise into the current state of execution (i.e., return the value of the promise if it was fulfilled or throw an exception if it was rejected). This is called "unwrapping" the promise. Waiting on a promise will by default unwrap the promise state.

You can force a promise to resolve and not unwrap the state of the promise by passing false to the first argument of the wait function:

$promise = new Promise();
$promise->reject('foo');
// This will not throw an exception. It simply ensures the promise has
// been resolved.
$promise->wait(false);

When unwrapping a promise, the resolved value of the promise will be waited upon until the unwrapped value is not a promise. This means that if you resolve promise A with a promise B and unwrap promise A, the value returned by the wait function will be the value delivered to promise B.

Note: when you do not unwrap the promise, no value is returned.

Cancellation

You can cancel a promise that has not yet been fulfilled using the cancel() method of a promise. When creating a promise you can provide an optional cancel function that when invoked cancels the action of computing a resolution of the promise.

API

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.

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.

FulfilledPromise

A fulfilled promise can be created to represent a promise that has been fulfilled.

use GuzzleHttp\Promise\FulfilledPromise;

$promise = new FulfilledPromise('value');

// Fulfilled callbacks are immediately invoked.
$promise->then(function ($value) {
    echo $value;
});

RejectedPromise

A rejected promise can be created to represent a promise that has been rejected.

use GuzzleHttp\Promise\RejectedPromise;

$promise = new RejectedPromise('Error');

// Rejected callbacks are immediately invoked.
$promise->then(null, function ($reason) {
    echo $reason;
});

Promise Interoperability

This library works with foreign promises that have a then method. This means you can use Guzzle promises with React promises for example. When a foreign promise is returned inside of a then method callback, promise resolution will occur recursively.

// Create a React promise
$deferred = new React\Promise\Deferred();
$reactPromise = $deferred->promise();

// Create a Guzzle promise that is fulfilled with a React promise.
$guzzlePromise = new GuzzleHttp\Promise\Promise();
$guzzlePromise->then(function ($value) use ($reactPromise) {
    // Do something something with the value...
    // Return the React promise
    return $reactPromise;
});

Please note that wait and cancel chaining is no longer possible when forwarding a foreign promise. You will need to wrap a third-party promise with a Guzzle promise in order to utilize wait and cancel functions with foreign promises.

Event Loop Integration

In order to keep the stack size constant, Guzzle promises are resolved asynchronously using a task queue. When waiting on promises synchronously, the task queue will be automatically run to ensure that the blocking promise and any forwarded promises are resolved. When using promises asynchronously in an event loop, you will need to run the task queue on each tick of the loop. If you do not run the task queue, then promises will not be resolved.

You can run the task queue using the run() method of the global task queue instance.

// Get the global task queue
$queue = GuzzleHttp\Promise\Utils::queue();
$queue->run();

For example, you could use Guzzle promises with React using a short periodic timer. Avoid zero-interval timers because they may keep the loop busy even when there is no promise work to run.

$loop = React\EventLoop\Factory::create();
$loop->addPeriodicTimer(0.01, [$queue, 'run']);

Implementation Notes

Promise Resolution and Chaining is Handled Iteratively

By shuffling pending handlers from one owner to another, promises are resolved iteratively, allowing for "infinite" then chaining.

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Promise\Promise;

$parent = new Promise();
$p = $parent;

for ($i = 0; $i < 1000; $i++) {
    $p = $p->then(function ($v) {
        // The stack size remains constant (a good thing)
        echo xdebug_get_stack_depth() . ', ';
        return $v + 1;
    });
}

$parent->resolve(0);
var_dump($p->wait()); // int(1000)

When a promise is fulfilled or rejected with a non-promise value, the promise then takes ownership of the handlers of each child promise and delivers values down the chain without using recursion.

When a promise is resolved with another promise, the original promise transfers all of its pending handlers to the new promise. When the new promise is eventually resolved, all of the pending handlers are delivered the forwarded value.

A Promise is the Deferred

Some promise libraries implement promises using a deferred object to represent a computation and a promise object to represent the delivery of the result of the computation. This is a nice separation of computation and delivery because consumers of the promise cannot modify the value that will be eventually delivered.

One side effect of being able to implement promise resolution and chaining iteratively is that you need to be able for one promise to reach into the state of another promise to shuffle around ownership of handlers. In order to achieve this without making the handlers of a promise publicly mutable, a promise is also the deferred value, allowing promises of the same parent class to reach into and modify the private properties of promises of the same type. While this does allow consumers of the value to modify the resolution or rejection of the deferred, it is a small price to pay for keeping the stack size constant.

$promise = new Promise();
$promise->then(function ($value) { echo $value; });
// The promise is the deferred value, so you can deliver a value to it.
$promise->resolve('foo');
// prints "foo"

Upgrading

See UPGRADING.md for package upgrade notes.

Security

If 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 for more information.

License

Guzzle is made available under the MIT License (MIT). Please see License File for more information.

For Enterprise

Available as part of the Tidelift Subscription

The 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.

Source
1# Guzzle Promises
2
3[Promises/A+](https://promisesaplus.com/) implementation that handles promise
4chaining and resolution iteratively, allowing for "infinite" promise chaining
5while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/)
6for a general introduction to promises.
7
8- [Features](#features)
9- [Quick start](#quick-start)
10- [Synchronous wait](#synchronous-wait)
11- [Cancellation](#cancellation)
12- [API](#api)
13 - [Promise](#promise)
14 - [FulfilledPromise](#fulfilledpromise)
15 - [RejectedPromise](#rejectedpromise)
16- [Promise interop](#promise-interop)
17- [Implementation notes](#implementation-notes)
18
19
20## Features
21
22- [Promises/A+](https://promisesaplus.com/) implementation.
23- Promise resolution and chaining is handled iteratively, allowing for
24 "infinite" promise chaining.
25- Promises have a synchronous `wait` method.
26- Promises can be cancelled.
27- Works with any object that has a `then` function.
28- C# style async/await coroutine promises using
29 `GuzzleHttp\Promise\Coroutine::of()`.
30
31
32## Installation
33
34```shell
35composer require guzzlehttp/promises
36```
37
38
39## Version Guidance
40
41| Version | Status | PHP Version |
42|---------|---------------------|--------------|
43| 1.x | Security fixes only | >=5.5,<8.3 |
44| 2.x | Latest | >=7.2.5,<8.7 |
45
46
47## Quick Start
48
49A *promise* represents the eventual result of an asynchronous operation. The
50primary way of interacting with a promise is through its `then` method, which
51registers callbacks to receive either a promise's eventual value or the reason
52why the promise cannot be fulfilled.
53
54### Callbacks
55
56Callbacks are registered with the `then` method by providing an optional
57`$onFulfilled` followed by an optional `$onRejected` function.
58
59
60```php
61use GuzzleHttp\Promise\Promise;
62
63$promise = new Promise();
64$promise->then(
65 // $onFulfilled
66 function ($value) {
67 echo 'The promise was fulfilled.';
68 },
69 // $onRejected
70 function ($reason) {
71 echo 'The promise was rejected.';
72 }
73);
74```
75
76*Resolving* a promise means that you either fulfill a promise with a *value* or
77reject a promise with a *reason*. Resolving a promise triggers callbacks
78registered with the promise's `then` method. These callbacks are triggered
79only once and in the order in which they were added.
80
81### Resolving a Promise
82
83Promises are fulfilled using the `resolve($value)` method. Resolving a promise
84with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger
85all of the onFulfilled callbacks (resolving a promise with a rejected promise
86will reject the promise and trigger the `$onRejected` callbacks).
87
88```php
89use GuzzleHttp\Promise\Promise;
90
91$promise = new Promise();
92$promise
93 ->then(function ($value) {
94 // Return a value and don't break the chain
95 return "Hello, " . $value;
96 })
97 // This then is executed after the first then and receives the value
98 // returned from the first then.
99 ->then(function ($value) {
100 echo $value;
101 });
102
103// Resolving the promise triggers the $onFulfilled callbacks and outputs
104// "Hello, reader."
105$promise->resolve('reader.');
106```
107
108### Promise Forwarding
109
110Promises can be chained one after the other. Each then in the chain is a new
111promise. The return value of a promise is what's forwarded to the next
112promise in the chain. Returning a promise in a `then` callback will cause the
113subsequent promises in the chain to only be fulfilled when the returned promise
114has been fulfilled. The next promise in the chain will be invoked with the
115resolved value of the promise.
116
117```php
118use GuzzleHttp\Promise\Promise;
119
120$promise = new Promise();
121$nextPromise = new Promise();
122
123$promise
124 ->then(function ($value) use ($nextPromise) {
125 echo $value;
126 return $nextPromise;
127 })
128 ->then(function ($value) {
129 echo $value;
130 });
131
132// Triggers the first callback and outputs "A"
133$promise->resolve('A');
134// Triggers the second callback and outputs "B"
135$nextPromise->resolve('B');
136```
137
138### Promise Rejection
139
140When a promise is rejected, the `$onRejected` callbacks are invoked with the
141rejection reason.
142
143```php
144use GuzzleHttp\Promise\Promise;
145
146$promise = new Promise();
147$promise->then(null, function ($reason) {
148 echo $reason;
149});
150
151$promise->reject('Error!');
152// Outputs "Error!"
153```
154
155### Rejection Forwarding
156
157If an exception is thrown in an `$onRejected` callback, subsequent
158`$onRejected` callbacks are invoked with the thrown exception as the reason.
159
160```php
161use GuzzleHttp\Promise\Promise;
162
163$promise = new Promise();
164$promise->then(null, function ($reason) {
165 throw new Exception($reason);
166})->then(null, function ($reason) {
167 assert($reason->getMessage() === 'Error!');
168});
169
170$promise->reject('Error!');
171```
172
173You can also forward a rejection down the promise chain by returning a
174`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or
175`$onRejected` callback.
176
177```php
178use GuzzleHttp\Promise\Promise;
179use GuzzleHttp\Promise\RejectedPromise;
180
181$promise = new Promise();
182$promise->then(null, function ($reason) {
183 return new RejectedPromise($reason);
184})->then(null, function ($reason) {
185 assert($reason === 'Error!');
186});
187
188$promise->reject('Error!');
189```
190
191If an exception is not thrown in a `$onRejected` callback and the callback
192does not return a rejected promise, downstream `$onFulfilled` callbacks are
193invoked using the value returned from the `$onRejected` callback.
194
195```php
196use GuzzleHttp\Promise\Promise;
197
198$promise = new Promise();
199$promise
200 ->then(null, function ($reason) {
201 return "It's ok";
202 })
203 ->then(function ($value) {
204 assert($value === "It's ok");
205 });
206
207$promise->reject('Error!');
208```
209
210
211## Synchronous Wait
212
213You can synchronously force promises to complete using a promise's `wait`
214method. When creating a promise, you can provide a wait function that is used
215to synchronously force a promise to complete. When a wait function is invoked
216it is expected to deliver a value to the promise or reject the promise. If the
217wait function does not deliver a value, then an exception is thrown. The wait
218function provided to a promise constructor is invoked when the `wait` function
219of the promise is called.
220
221```php
222$promise = new Promise(function () use (&$promise) {
223 $promise->resolve('foo');
224});
225
226// Calling wait will return the value of the promise.
227echo $promise->wait(); // outputs "foo"
228```
229
230If a throwable is encountered while invoking the wait function of a promise,
231the promise is rejected with the throwable and the throwable is thrown.
232
233```php
234$promise = new Promise(function () use (&$promise) {
235 throw new Exception('foo');
236});
237
238$promise->wait(); // throws the exception.
239```
240
241Calling `wait` on a promise that has been fulfilled will not trigger the wait
242function. It will simply return the previously resolved value.
243
244```php
245$promise = new Promise(function () { die('this is not called!'); });
246$promise->resolve('foo');
247echo $promise->wait(); // outputs "foo"
248```
249
250Calling `wait` on a promise that has been rejected will throw. If the rejection
251reason is an instance of `\Throwable` the reason is thrown.
252Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason
253can be obtained by calling the `getReason` method of the exception.
254
255```php
256$promise = new Promise();
257$promise->reject('foo');
258$promise->wait();
259```
260
261> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo'
262
263### Unwrapping a Promise
264
265When synchronously waiting on a promise, you are joining the state of the
266promise into the current state of execution (i.e., return the value of the
267promise if it was fulfilled or throw an exception if it was rejected). This is
268called "unwrapping" the promise. Waiting on a promise will by default unwrap
269the promise state.
270
271You can force a promise to resolve and *not* unwrap the state of the promise
272by passing `false` to the first argument of the `wait` function:
273
274```php
275$promise = new Promise();
276$promise->reject('foo');
277// This will not throw an exception. It simply ensures the promise has
278// been resolved.
279$promise->wait(false);
280```
281
282When unwrapping a promise, the resolved value of the promise will be waited
283upon until the unwrapped value is not a promise. This means that if you resolve
284promise A with a promise B and unwrap promise A, the value returned by the
285wait function will be the value delivered to promise B.
286
287**Note**: when you do not unwrap the promise, no value is returned.
288
289
290## Cancellation
291
292You can cancel a promise that has not yet been fulfilled using the `cancel()`
293method of a promise. When creating a promise you can provide an optional
294cancel function that when invoked cancels the action of computing a resolution
295of the promise.
296
297
298## API
299
300### Promise
301
302When creating a promise object, you can provide an optional `$waitFn` and
303`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is
304expected to resolve the promise. `$cancelFn` is a function with no arguments
305that is expected to cancel the computation of a promise. It is invoked when the
306`cancel()` method of a promise is called.
307
308```php
309use GuzzleHttp\Promise\Promise;
310
311$promise = new Promise(
312 function () use (&$promise) {
313 $promise->resolve('waited');
314 },
315 function () {
316 // do something that will cancel the promise computation (e.g., close
317 // a socket, cancel a database query, etc...)
318 }
319);
320
321assert('waited' === $promise->wait());
322```
323
324A promise has the following methods:
325
326- `then(?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface`
327
328 Appends fulfillment and rejection handlers to the promise, and returns a new
329 promise resolving to the return value of the called handler. If a handler is
330 omitted, the original fulfillment value or rejection reason is forwarded.
331
332- `otherwise(callable $onRejected) : PromiseInterface`
333
334 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.
335
336- `wait($unwrap = true) : mixed`
337
338 Synchronously waits on the promise to complete.
339
340 `$unwrap` controls whether or not the value of the promise is returned for a
341 fulfilled promise or if an exception is thrown if the promise is rejected.
342 This is set to `true` by default.
343
344- `cancel()`
345
346 Attempts to cancel the promise if possible. The promise being cancelled and
347 the parent most ancestor that has not yet been resolved will also be
348 cancelled. Any promises waiting on the cancelled promise to resolve will also
349 be cancelled.
350
351- `getState() : string`
352
353 Returns the state of the promise. One of `pending`, `fulfilled`, or
354 `rejected`.
355
356- `resolve($value)`
357
358 Fulfills the promise with the given `$value`.
359
360- `reject($reason)`
361
362 Rejects the promise with the given `$reason`.
363
364
365### FulfilledPromise
366
367A fulfilled promise can be created to represent a promise that has been
368fulfilled.
369
370```php
371use GuzzleHttp\Promise\FulfilledPromise;
372
373$promise = new FulfilledPromise('value');
374
375// Fulfilled callbacks are immediately invoked.
376$promise->then(function ($value) {
377 echo $value;
378});
379```
380
381
382### RejectedPromise
383
384A rejected promise can be created to represent a promise that has been
385rejected.
386
387```php
388use GuzzleHttp\Promise\RejectedPromise;
389
390$promise = new RejectedPromise('Error');
391
392// Rejected callbacks are immediately invoked.
393$promise->then(null, function ($reason) {
394 echo $reason;
395});
396```
397
398
399## Promise Interoperability
400
401This library works with foreign promises that have a `then` method. This means
402you can use Guzzle promises with [React promises](https://github.com/reactphp/promise)
403for example. When a foreign promise is returned inside of a then method
404callback, promise resolution will occur recursively.
405
406```php
407// Create a React promise
408$deferred = new React\Promise\Deferred();
409$reactPromise = $deferred->promise();
410
411// Create a Guzzle promise that is fulfilled with a React promise.
412$guzzlePromise = new GuzzleHttp\Promise\Promise();
413$guzzlePromise->then(function ($value) use ($reactPromise) {
414 // Do something something with the value...
415 // Return the React promise
416 return $reactPromise;
417});
418```
419
420Please note that wait and cancel chaining is no longer possible when forwarding
421a foreign promise. You will need to wrap a third-party promise with a Guzzle
422promise in order to utilize wait and cancel functions with foreign promises.
423
424
425### Event Loop Integration
426
427In order to keep the stack size constant, Guzzle promises are resolved
428asynchronously using a task queue. When waiting on promises synchronously, the
429task queue will be automatically run to ensure that the blocking promise and
430any forwarded promises are resolved. When using promises asynchronously in an
431event loop, you will need to run the task queue on each tick of the loop. If
432you do not run the task queue, then promises will not be resolved.
433
434You can run the task queue using the `run()` method of the global task queue
435instance.
436
437```php
438// Get the global task queue
439$queue = GuzzleHttp\Promise\Utils::queue();
440$queue->run();
441```
442
443For example, you could use Guzzle promises with React using a short periodic
444timer. Avoid zero-interval timers because they may keep the loop busy even when
445there is no promise work to run.
446
447```php
448$loop = React\EventLoop\Factory::create();
449$loop->addPeriodicTimer(0.01, [$queue, 'run']);
450```
451
452
453## Implementation Notes
454
455### Promise Resolution and Chaining is Handled Iteratively
456
457By shuffling pending handlers from one owner to another, promises are
458resolved iteratively, allowing for "infinite" then chaining.
459
460```php
461<?php
462require 'vendor/autoload.php';
463
464use GuzzleHttp\Promise\Promise;
465
466$parent = new Promise();
467$p = $parent;
468
469for ($i = 0; $i < 1000; $i++) {
470 $p = $p->then(function ($v) {
471 // The stack size remains constant (a good thing)
472 echo xdebug_get_stack_depth() . ', ';
473 return $v + 1;
474 });
475}
476
477$parent->resolve(0);
478var_dump($p->wait()); // int(1000)
479
480```
481
482When a promise is fulfilled or rejected with a non-promise value, the promise
483then takes ownership of the handlers of each child promise and delivers values
484down the chain without using recursion.
485
486When a promise is resolved with another promise, the original promise transfers
487all of its pending handlers to the new promise. When the new promise is
488eventually resolved, all of the pending handlers are delivered the forwarded
489value.
490
491### A Promise is the Deferred
492
493Some promise libraries implement promises using a deferred object to represent
494a computation and a promise object to represent the delivery of the result of
495the computation. This is a nice separation of computation and delivery because
496consumers of the promise cannot modify the value that will be eventually
497delivered.
498
499One side effect of being able to implement promise resolution and chaining
500iteratively is that you need to be able for one promise to reach into the state
501of another promise to shuffle around ownership of handlers. In order to achieve
502this without making the handlers of a promise publicly mutable, a promise is
503also the deferred value, allowing promises of the same parent class to reach
504into and modify the private properties of promises of the same type. While this
505does allow consumers of the value to modify the resolution or rejection of the
506deferred, it is a small price to pay for keeping the stack size constant.
507
508```php
509$promise = new Promise();
510$promise->then(function ($value) { echo $value; });
511// The promise is the deferred value, so you can deliver a value to it.
512$promise->resolve('foo');
513// prints "foo"
514```
515
516
517## Upgrading
518
519See [UPGRADING.md](UPGRADING.md) for package upgrade notes.
520
521
522## Security
523
524If 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://github.com/guzzle/promises/security/policy) for more information.
525
526
527## License
528
529Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.
530
531
532## For Enterprise
533
534Available as part of the Tidelift Subscription
535
536The 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://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)