Skip to content

Commit ab70f56

Browse files
authored
Merge pull request #295 from ezimuel/add/promise-retry-mechanism
Add Promise documentation for retry mechanism
2 parents 282412a + 8e4f948 commit ab70f56

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

components/promise.rst

+36
Original file line numberDiff line numberDiff line change
@@ -81,5 +81,41 @@ executed if the request results in an error::
8181
}
8282
);
8383

84+
The failure callback can also return a ``Promise``. This can be useful to implement a retry
85+
mechanism, as follows:
86+
87+
use Http\Discovery\HttpAsyncClientDiscovery;
88+
use Http\Discovery\Psr17FactoryDiscovery;
89+
90+
$client = HttpAsyncClientDiscovery::find();
91+
$requestFactory = Psr17FactoryDiscovery::findRequestFactory();
92+
$retries = 2; // number of HTTP retries
93+
$request = $requestFactory->createRequest("GET", "http://localhost:8080/test");
94+
95+
// success callback
96+
$success = function (ResponseInterface $response) {
97+
return $response;
98+
};
99+
// failure callback
100+
$failure = function (Exception $e) use ($client, $request) {
101+
// $request can be changed, e.g. using a Round-Robin algorithm
102+
103+
// try another execution
104+
return $client->sendAsyncRequest($request);
105+
};
106+
107+
$promise = $client->sendAsyncRequest($request);
108+
for ($i=0; $i < $retries; $i++) {
109+
$promise = $promise->then($success, $failure);
110+
}
111+
// Add the last callable to manage the exceeded maximum number of retries
112+
$promise->then($success, function(\Exception $e) {
113+
throw new \Exception(sprintf(
114+
"Exceeded maximum number of retries (%d): %s",
115+
$retries,
116+
$e->getMessage()
117+
));
118+
});
119+
84120
.. _`Promise PSR`: https://groups.google.com/forum/?fromgroups#!topic/php-fig/wzQWpLvNSjs
85121
.. _Promises/A+: https://promisesaplus.com

0 commit comments

Comments
 (0)