|
1 | 1 | Promise
|
2 | 2 | =======
|
3 | 3 |
|
4 |
| -Promise used for asynchronous HTTP requests. |
5 |
| - |
6 |
| -This will eventually be removed/deprecated and replaced with the upcoming Promise PSR. |
| 4 | +When sending asynchronous HTTP requests, a promise is returned. The promise acts |
| 5 | +as a proxy for the response or error result, which is not yet known. |
7 | 6 |
|
8 | 7 | .. note::
|
9 | 8 |
|
10 |
| - Contract for the ``Http\Promise\Promise`` is temporary until `PSR is released`_. |
11 |
| - Once it is out, we will use this PSR in the main client and deprecate the old contract. |
| 9 | + Work is underway for a `Promise PSR`_. When that PSR has been released, we |
| 10 | + will use it in HTTPlug and deprecate our ``Http\Promise\Promise`` interface. |
| 11 | + |
| 12 | +Asynchronous requests |
| 13 | +--------------------- |
| 14 | + |
| 15 | +Asynchronous requests enable non-blocking HTTP operations. To execute such a |
| 16 | +request with HTTPlug:: |
| 17 | + |
| 18 | + $request = $messageFactory->createRequest('GET', 'http://php-http.org'); |
| 19 | + |
| 20 | + // Where $client implements HttpAsyncClient |
| 21 | + $promise = $client->sendAsyncRequest($request); |
| 22 | + |
| 23 | + // This code will be executed right after the request is sent, but before |
| 24 | + // the response is returned. |
| 25 | + echo 'Wow, non-blocking!'; |
| 26 | + |
| 27 | +See :ref:`message-factory` on how to use message factories. |
| 28 | + |
| 29 | +Wait |
| 30 | +---- |
| 31 | + |
| 32 | +The ``$promise`` that is returned implements ``Http\Promise\Promise``. At this |
| 33 | +point in time, the response is not known yet. You can be polite and wait for |
| 34 | +that response to arrive:: |
| 35 | + |
| 36 | + try { |
| 37 | + $response = $promise->wait(); |
| 38 | + } catch (\Exception $exception) { |
| 39 | + echo $exception->getMessage(); |
| 40 | + } |
| 41 | + |
| 42 | +Then |
| 43 | +---- |
| 44 | + |
| 45 | +Instead of waiting, however, you can handle things asynchronously. Call the |
| 46 | +``then`` method with two arguments: one callback that will be executed if the |
| 47 | +request turns out to be successful and/or a second callback that will be |
| 48 | +executed if the request results in an error:: |
| 49 | + |
| 50 | + $promise->then( |
| 51 | + // The success callback |
| 52 | + function (ResponseInterface $response) { |
| 53 | + echo 'Yay, we have a shiny new response!'; |
| 54 | + |
| 55 | + return $response; |
| 56 | + }, |
| 57 | + |
| 58 | + // The failure callback |
| 59 | + function (\Exception $exception) { |
| 60 | + echo 'Oh darn, we have a problem'; |
| 61 | + |
| 62 | + throw $exception; |
| 63 | + } |
| 64 | + ); |
12 | 65 |
|
13 |
| -.. _`PSR is released`: https://groups.google.com/forum/?fromgroups#!topic/php-fig/wzQWpLvNSjs |
| 66 | +.. _`Promise PSR`: https://groups.google.com/forum/?fromgroups#!topic/php-fig/wzQWpLvNSjs |
0 commit comments