@@ -81,5 +81,41 @@ executed if the request results in an error::
81
81
}
82
82
);
83
83
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\D iscovery\H ttpAsyncClientDiscovery;
88
+ use Http\D iscovery\P sr17FactoryDiscovery;
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(\E xception $e) {
113
+ throw new \E xception(sprintf(
114
+ "Exceeded maximum number of retries (%d): %s",
115
+ $retries,
116
+ $e->getMessage()
117
+ ));
118
+ });
119
+
84
120
.. _`Promise PSR` : https://groups.google.com/forum/?fromgroups#!topic/php-fig/wzQWpLvNSjs
85
121
.. _Promises/A+ : https://promisesaplus.com
0 commit comments