Skip to content

Commit

Permalink
Merge pull request #295 from ezimuel/add/promise-retry-mechanism
Browse files Browse the repository at this point in the history
Add Promise documentation for retry mechanism
  • Loading branch information
dbu committed Apr 29, 2022
2 parents 282412a + 8e4f948 commit ab70f56
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions components/promise.rst
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,41 @@ executed if the request results in an error::
}
);

The failure callback can also return a ``Promise``. This can be useful to implement a retry
mechanism, as follows:

use Http\Discovery\HttpAsyncClientDiscovery;
use Http\Discovery\Psr17FactoryDiscovery;

$client = HttpAsyncClientDiscovery::find();
$requestFactory = Psr17FactoryDiscovery::findRequestFactory();
$retries = 2; // number of HTTP retries
$request = $requestFactory->createRequest("GET", "http://localhost:8080/test");

// success callback
$success = function (ResponseInterface $response) {
return $response;
};
// failure callback
$failure = function (Exception $e) use ($client, $request) {
// $request can be changed, e.g. using a Round-Robin algorithm

// try another execution
return $client->sendAsyncRequest($request);
};

$promise = $client->sendAsyncRequest($request);
for ($i=0; $i < $retries; $i++) {
$promise = $promise->then($success, $failure);
}
// Add the last callable to manage the exceeded maximum number of retries
$promise->then($success, function(\Exception $e) {
throw new \Exception(sprintf(
"Exceeded maximum number of retries (%d): %s",
$retries,
$e->getMessage()
));
});

.. _`Promise PSR`: https://groups.google.com/forum/?fromgroups#!topic/php-fig/wzQWpLvNSjs
.. _Promises/A+: https://promisesaplus.com

0 comments on commit ab70f56

Please sign in to comment.